簡體   English   中英

點擊動畫向下滾動

[英]scroll down on click with animations

我有 html 頁面。 我想用動畫向下滾動按鈕單擊(按鈕的類為 "s_down_button" )。

我需要在 element_height + 20 像素向下滾動屏幕。

element_height - 具有“tp-bgimg”類的元素的高度

所以我嘗試:

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);
    }); 

});

但我收到一個錯誤:

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

其中 600 是以毫秒為單位的動畫時間。 有關更多信息,請查看animate jquery doc

您正在尋找的功能是:

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

我喜歡做的是創建一個 scrollTo 函數來調用這行代碼:

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

這應該有效:

$(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);
    });
});

如果您的元素不在頁面的最頂部,您應該添加偏移量:

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

所以可變滾動高度是:

var scroll_height = element_height + offsetOfElement +20;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM