简体   繁体   English

点击动画向下滚动

[英]scroll down on click with animations

I have html page.我有 html 页面。 And I want to scroll down on button click ( button has class "s_down_button" ) with animation.我想用动画向下滚动按钮单击(按钮的类为 "s_down_button" )。

I need scroll screen on element_height + 20 pixels down.我需要在 element_height + 20 像素向下滚动屏幕。

element_height - height of element with "tp-bgimg" class element_height - 具有“tp-bgimg”类的元素的高度

So I try:所以我尝试:

jQuery(document).ready(function($) {

    $(".s_down_button").click(function(){
        var element_height = $(".tp-bgimg").height();
        var scroll_height = element_height +20;
        $('body').scrollTo(scroll_height);
    }); 

});

but I get an error:但我收到一个错误:

Uncaught TypeError: $(...).scrollTo is not a function
$("html, body").animate({ scrollTop: scroll_height }, 600);

where 600 is time of animation in miliseconds.其中 600 是以毫秒为单位的动画时间。 For more info look at animate jquery doc有关更多信息,请查看animate jquery doc

The function you are looking for is:您正在寻找的功能是:

$('body').animate({scrollTop: positionToScrollTo}, 500);

What I like to do is create a scrollTo function that calls this line of code:我喜欢做的是创建一个 scrollTo 函数来调用这行代码:

function scrollTo(position) {
    $('body').animate({scrollTop: position}, 500);
}

This should work:这应该有效:

$(document).ready(function() {
    $(".s_down_button").click(function(){
        var element_height = $(".tp-bgimg").height();
        var scroll_height = element_height +20;
        $('body').animate({scrollTop: scroll_height }, 500);
    });
});

If your element is not on very top of the page you should add the offset:如果您的元素不在页面的最顶部,您应该添加偏移量:

var offsetOfElement = $(".tp-bgimg").offset().top;

So the variable scroll height is:所以可变滚动高度是:

var scroll_height = element_height + offsetOfElement +20;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM