Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>滚动到页面指定元素</title>
  <style type="text/css">
    #target{
      position: absolute;
      top:2000px;
      width: 100%;
      background: #49a9ee;
    }
    #btn{
      position: fixed;
      top:0;
      left:0;
      padding:5px 20px;
      background: #00a854;
    }
  </style>
</head>
<body>
<button type="button" id="btn">scroll</button>
<div id="target">Hello world</div>
<script>
  let btn=document.getElementById('btn');
  let target=document.getElementById('target');
  function animateScroll(element,speed) {
    let rect=element.getBoundingClientRect();
    //获取元素相对窗口的top值,此处应加上窗口本身的偏移
    let top=window.pageYOffset+rect.top;
    let currentTop=0;
    let requestId;
    //采用requestAnimationFrame,平滑动画
    function step(timestamp) {
      currentTop+=speed;
      if(currentTop<=top){
        window.scrollTo(0,currentTop);
        requestId=window.requestAnimationFrame(step);
      }else{
        window.cancelAnimationFrame(requestId);
      }
    }
    window.requestAnimationFrame(step);
  }
  btn.onclick=function (e) {
    animateScroll(target,50);
  };
</script>
</body>
</html>
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
WangShuXian6pro
0viewers