javascript将div滚动到具有平滑滚动效果的视图中?

时间:2015-06-17 14:59:34

标签: javascript scroll

当用户点击div时,我使用以下javascript代码将div滚动到视图中。

    <script>
    function showDiv2() {
   document.getElementById('about').style.display = "none";
   document.getElementById('terms').style.display = "none";
   document.getElementById('breaker').style.display = "block";
   document.getElementById('contact_us').style.display = "block";
   document.getElementById( 'contact_us' ).scrollIntoView('slow');
}
</script>

此代码可以工作并将div滚动到视图中,但没有效果,而不是页面平滑地向下滚动到我的div它只是跳转到div。有没有办法让我顺利地慢慢向下滚动到我的div?感谢

2 个答案:

答案 0 :(得分:1)

根据Element.scrollIntoView() documentation试试这个:

element.scrollIntoView({block: "end", behavior: "smooth"});

但你必须记住,这是一个实验性功能,仅适用于Firefox

答案 1 :(得分:0)

您可以将for循环与window.scrollTo和setTimeout一起使用,以使用纯Javascript平滑滚动。要使用我的scrollToSmoothly函数滚动到某个元素,请执行以下操作:scrollToSmoothly(elem.offsetTop)(假设elem是DOM元素)。

function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
     if(isNaN(pos)){
      throw "Position must be a number";
     }
     if(pos<0){
     throw "Position can not be negative";
     }
    var currentPos = window.scrollY||window.screenTop;
    if(currentPos<pos){
    var t = 10;
       for(let i = currentPos; i <= pos; i+=10){
       t+=10;
        setTimeout(function(){
        window.scrollTo(0, i);
        }, t/2);
      }
    } else {
    time = time || 2;
       var i = currentPos;
       var x;
      x = setInterval(function(){
         window.scrollTo(0, i);
         i -= 10;
         if(i<=pos){
          clearInterval(x);
         }
     }, time);
      }
}

演示:

<button onClick="scrollToDiv()">Scroll To Element</button>
<div style="margin: 1000px 0px; text-align: center;">Div element<p/>
<button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button>
</div>
<script>
function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
     if(isNaN(pos)){
      throw "Position must be a number";
     }
     if(pos<0){
     throw "Position can not be negative";
     }
    var currentPos = window.scrollY||window.screenTop;
    if(currentPos<pos){
    var t = 10;
       for(let i = currentPos; i <= pos; i+=10){
       t+=10;
        setTimeout(function(){
      	window.scrollTo(0, i);
        }, t/2);
      }
    } else {
    time = time || 2;
       var i = currentPos;
       var x;
      x = setInterval(function(){
         window.scrollTo(0, i);
         i -= 10;
         if(i<=pos){
          clearInterval(x);
         }
     }, time);
      }
}
function scrollToDiv(){
  var elem = document.querySelector("div");
  scrollToSmoothly(elem.offsetTop);
}
</script>