scrollIntoView在Edge中不平滑

问题描述 投票:0回答:1

我正在使用vanilla JS将按钮平滑地向下滚动到div元素(以id为目标)

我有这个作为我的代码:

this.myButton.addEventListener("click",load_section);
function load_section() {  
        document.querySelector('#myDiv').scrollIntoView({ block: 'end',  behavior: 'smooth' });  
    }

在所有其他浏览器中,这将平滑地滚动到该部分。在Edge中,它只是跳到它。我需要更改什么才能使其平滑滚动到该部分

javascript microsoft-edge smooth-scrolling js-scrollintoview
1个回答
0
投票

您可以使用带有window.scrollTo和setTimeout的for循环来使用普通Javascript平滑滚动。使用我的scrollToSmoothly函数滚动到一个元素:scrollToSmoothly(elem.offsetTop)(假设elem是一个DOM元素)。您可以使用此功能平滑滚动到文档中的任何y位置。

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>
© www.soinside.com 2019 - 2024. All rights reserved.