js點選平滑定位到指定元素程式碼例項

antzone發表於2017-04-06

本章節分享一段程式碼例項,它實現了更為人性化的錨點定位功能。點選一個按鈕可以實現平滑的定位到指定元素功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>螞蟻部落</title>
<style>
*{
  margin:0px;
  padding:0px;
}
input{
  position:fixed;
  left:50px;
  top:50px;
}
#antzone{
  width:200px;
  height:200px;
  background:green;
  margin-bottom:800px;
  margin-top:300px;
  margin-left:300px;
}
</style>
<script type="text/javascript">
function elementPosition(obj) {
  var curleft = 0, curtop = 0;
  if (obj.offsetParent) {
   curleft = obj.offsetLeft;
   curtop = obj.offsetTop;
   while (obj = obj.offsetParent) {
    curleft += obj.offsetLeft;
    curtop += obj.offsetTop;
   }
  }
  return { x: curleft, y: curtop };
}
 
function ScrollToControl(id){
  var elem = document.getElementById(id);
  var scrollPos = elementPosition(elem).y;
  scrollPos = scrollPos - document.documentElement.scrollTop;
  var remainder = scrollPos % 50;
  var repeatTimes = (scrollPos - remainder) / 50;
  ScrollSmoothly(scrollPos,repeatTimes);
  window.scrollBy(0,remainder);
}
 
var repeatCount = 0;
var cTimeout;
var timeoutIntervals = new Array();
var timeoutIntervalSpeed;
 
function ScrollSmoothly(scrollPos,repeatTimes){
  if(repeatCount < repeatTimes){
    window.scrollBy(0,50);
  }
  else{
    repeatCount = 0;
    clearTimeout(cTimeout);
    return;
  }
  repeatCount++;
  cTimeout = setTimeout("ScrollSmoothly('"+scrollPos+"','"+repeatTimes+"')",10);
}
window.onload=function(){
  var obt=document.getElementById("bt");
  obt.onclick=function(){
    ScrollToControl("antzone");
  }
}
</script>
</head>
<body>
<input type="button" id="bt" value="檢視效果"/>
<div id="antzone"></div>
</body>
</html>


相關文章