js点击平滑定位到指定元素代码实例

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它实现了更为人性化的锚点定位功能。点击一个按钮可以实现平滑的定位到指定元素功能。

代码实例如下:

<!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>

回复

我来回复
  • 暂无回复内容