在html / js中没有点击功能的滚动页面动作 [英] Scrolling page action without click function in html/js

查看:115
本文介绍了在html / js中没有点击功能的滚动页面动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $(document).ready(function( ){
$(#button)。click(function(e){
e.preventDefault();
$('html,body')。animate({
scrollTop:$($。attr(this,'href'))。offset()。top
},8000);
});
});

但是我想让它在没有点击任何按钮的情况下工作。当页面加载时,它应该滚动。

  $(document).ready(function(){
$ ('html,body')。animate({
scrollTop:$($。attr(this,'href'))。offset()。top
},8000);
} );


解决方案

我个人并不喜欢使用jQuery的animate功能,所以我实现了我自己的。您可以通过增加或减少setTimeout函数的时间来改变它的速度。

  $(document).ready(function (){
var pixels = $('a')。position();
Scroll(pixels.top);
});

函数滚动(像素){
if(像素> 0){
window.scrollBy(0,1);
scrollTimeout = setTimeout(function(){
Scroll(pixels-1);
},1);
}
else {
clearTimeout(scrollTimeout)
return;


这是我提到的小提琴的链接展示我认为你正在努力做的事情。
让我知道这是否有帮助!



https: //jsfiddle.net/ogb4t33q/


I am using this code to scroll the page after clicking a button:

$(document).ready(function() {
  $("#button").click(function(e) {
    e.preventDefault();
    $('html, body').animate({
      scrollTop: $($.attr(this, 'href')).offset().top
    }, 8000);
  });
});

But I want to make it work without clicking any button. When the page loads, it should scroll. I used this code and it does not work:

$(document).ready(function() {
  $('html, body').animate({
    scrollTop: $($.attr(this, 'href')).offset().top
  }, 8000);
});

解决方案

I personally am not a big fan of using jQuery's animate function, so i implemented my own. You can change the speed of it by increasing or decreasing the time of the setTimeout function.

$(document).ready(function() {
    var pixels = $('a').position();
    Scroll(pixels.top);
});

function Scroll(pixels) {
    if( pixels > 0){
        window.scrollBy(0,1);
        scrollTimeout = setTimeout(function(){
            Scroll(pixels-1); 
        },1);
    }
    else {
        clearTimeout(scrollTimeout)
        return;
    }
}

Here is a link to the fiddle that i made to demonstrate what I think you are trying to do. Let me know if this helps!

https://jsfiddle.net/ogb4t33q/

这篇关于在html / js中没有点击功能的滚动页面动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆