[英]Jquery Smooth Scroll To DIV - Using ID value from Link
所以我的JQuery存在一些問題,我想滾動到特定的div。
HTML
<div id="searchbycharacter">
<a class="searchbychar" href="#" id="#0-9" onclick="return false">0-9 |</a>
<a class="searchbychar" href="#" id="#A" onclick="return false"> A |</a>
<a class="searchbychar" href="#" id="#B" onclick="return false"> B |</a>
<a class="searchbychar" href="#" id="#C" onclick="return false"> C |</a>
... Untill Z
</div>
<div id="0-9">
<p>some content</p>
</div>
<div id="A">
<p>some content</p>
</div>
<div id="B">
<p>some content</p>
</div>
<div id="C">
<p>some content</p>
</div>
... Untill Z
JQuery的
我想要的代碼是:在.searchbychar的點擊事件A TAG>獲取ID屬性值並滾動到那...
$( '.searchbychar' ).click(function() {
$('html, body').animate({
scrollTop: $('.searchbychar').attr('id').offset().top
}, 2000);
});
ID應該是唯一的,並且永遠不會使用以數字開頭的id,而是使用數據屬性來設置目標,如下所示:
<div id="searchbycharacter">
<a class="searchbychar" href="#" data-target="numeric">0-9 |</a>
<a class="searchbychar" href="#" data-target="A"> A |</a>
<a class="searchbychar" href="#" data-target="B"> B |</a>
<a class="searchbychar" href="#" data-target="C"> C |</a>
... Untill Z
</div>
至於jquery:
$(document).on('click','.searchbychar', function(event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
你可以這樣做:
$('.searchbychar').click(function () {
var divID = '#' + this.id;
$('html, body').animate({
scrollTop: $(divID).offset().top
}, 2000);
});
FYI
.
( 點 )就像你的第一行代碼一樣。 $( 'searchbychar' ).click(function() {
$('.searchbychar').attr('id')
將返回字符串ID而不是jQuery對象。 因此,您無法對其應用.offset()
方法。 這是我的解決方案:
<!-- jquery smooth scroll to id's -->
<script>
$(function() {
$('a[href*=\\#]:not([href=\\#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 500);
return false;
}
}
});
});
</script>
只需使用此代碼段,您就可以使用無限數量的哈希鏈接和相應的ID,而無需為每個哈希鏈接執行新的腳本。
我已經在另一個線程中解釋了它是如何工作的: https : //stackoverflow.com/a/28631803/4566435 (或者這里是我博客文章的直接鏈接 )
有關澄清,請告訴我。 希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.