单击javascript顺畅滚动

use*_*389 15 javascript scrolltop

我正在使用此链接:

<a class="" onclick="location.href='#top'" href="superContent">superContent</a>
Run Code Online (Sandbox Code Playgroud)

它同时做两件事:

  1. 将用户跳转到页面顶部
  2. 执行另一个(不相关的)ajax加载功能

一切都很好,除了我试图弄清楚如何让它更顺畅地滚动到顶部.我已经尝试添加.scroll将它附加到我的jquery scrollTo插件,但没有任何反应,这可能与我正在使用javascript onclick这一事实有关,而href属性完全做了其他事情.

有没有办法将动画平滑滚动附加到onclick ="location.href ='#top'"?

PRN*_*ios 40

试试这个,它动画了这个scrollTop()功能.

设置链接的ID:

<a id="link">link</a>
Run Code Online (Sandbox Code Playgroud)

要滚动的jquery:

$('#link').click(function(e){
  var $target = $('html,body');
  $target.animate({scrollTop: $target.height()}, 500);
});
Run Code Online (Sandbox Code Playgroud)

  • 由于这个问题是在没有jQuery标签的情况下提出的,所以我期待一个简单的JS解决方案. (4认同)
  • 'return false'绝对错在这里!请改用'function(e)..'和'e.preventDefault()'. (2认同)

vsy*_*ync 5

document.querySelector('button').addEventListener('click', function(){
   scrollTo( document.querySelector('aside'), Math.floor(Math.random() * 1000) + 1  , 600 );   
});
    
function scrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;
        
    var animateScroll = function(){        
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
}

//t = current time
//b = start value
//c = change in value
//d = duration
Math.easeInOutQuad = function (t, b, c, d) {
  t /= d/2;
  if (t < 1) return c/2*t*t + b;
  t--;
  return -c/2 * (t*(t-2) - 1) + b;
};
Run Code Online (Sandbox Code Playgroud)
button{ float:left; }
aside{ height:200px; width:50%; border:2px dashed red; overflow:auto; }
aside::before{
  content:''; 
  display:block; 
  height:1000px;  
  background: linear-gradient(#3f87a6, #ebf8e1, #f69d3c);
}
Run Code Online (Sandbox Code Playgroud)
<button>click to random scroll</button>
<aside></aside>
Run Code Online (Sandbox Code Playgroud)