[英]On click scroll to the top with 100px more
我使用一頁網站,當我單擊菜單按鈕時,它會向下滾動到某些div的頂部...但是因為我使用的是固定標頭,滾動到0px頂部,所以我需要像主體標簽中的padding一樣的100px top,但是我需要在函數中要說的是,我需要從頁面頂部滾動到100px之后,滾動到項目頂部。 這是我的代碼:
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
var x = $(this.hash).offset().top;
$('html,body').animate({scrollTop:x},2000);
});
});
如果我正確理解,只需在$(this.hash).offset().top
添加100px即可。
因為,偏移量是獲取相對於文檔的數據。
獲取第一個元素的當前坐標,或設置匹配元素集中相對於文檔的每個元素的坐標。 http://api.jquery.com/offset/
jQuery(document).ready(function($) { $(".scroll").click(function(event) { event.preventDefault(); var x = $(this).offset().top; $('html,body').animate({scrollTop: x - 100 }, 2000); }); });
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body style="height: 1000px; padding-top: 100px"> <div class="scroll">click to scroll to me</div> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.