jquery平滑滚动到DIV - 使用来自Link的ID值 [英] Jquery Smooth Scroll To DIV - Using ID value from Link
问题描述
所以我在使用我的JQuery时遇到了一些问题,我们可以将它们滚动到特定的div。
$ b
HTML
b$ b
< div id =searchbycharacter>
< a class =searchbycharhref =#id =#0-9onclick =return false> 0-9 |< / a>
< a class =searchbycharhref =#id =#Aonclick =return false> A |< / a>
< a class =searchbycharhref =#id =#Bonclick =return false> B |< / a>
< a class =searchbycharhref =#id =#Conclick =return false> C |< / a>
...直到Z
< / div>
< div id =0-9>
< p>一些内容< / p>
< / div>
< div id =A>
< p>一些内容< / p>
< / div>
< div id =B>
< p>一些内容< / p>
< / div>
< div id =C>
< p>一些内容< / p>
< / div>
...直到Z
JQuery
我想要的代码是:在.searchbychar的点击事件上标记>获取ID属性值并滚动到...
$ b $
$('.searchbychar').click(function(){
$('html,body') .animate({
scrollTop:$('。searchbychar')。attr('id')。offset()。top
},2000);
});
IDs是独一无二的,永远不会使用以数字开头的ID,使用data-attributes来设置目标,例如: >
< a class =searchbycharhref =#data-target =numeric> 0-9 |< / a>
< a class =searchbycharhref =#data-target =A> A |< / a>
< a class =searchbycharhref =#data-target =B> B |< / a>
< a class =searchbycharhref =#data-target =C> C |< / a>
...直到Z
< / div>
至于jquery:
<$ p $ ('click','。searchbychar',function(event){
event.preventDefault();
var target =#+ this.getAttribute('data-target');
$('html,body')。animate({
scrollTop:$(target).offset()。top
},2000 );
});
So i'm having some issues with my JQuery which is suppose to scroll to particular divs.
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
What i want the code to do is: On click event of an .searchbychar A TAG > Take the ID attributes value and scroll to that...
$( '.searchbychar' ).click(function() {
$('html, body').animate({
scrollTop: $('.searchbychar').attr('id').offset().top
}, 2000);
});
Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :
<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>
As for the jquery :
$(document).on('click','.searchbychar', function(event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
这篇关于jquery平滑滚动到DIV - 使用来自Link的ID值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!