gpt4 book ai didi

jQuery 动画滚动 : Can I limit the function to specific targets?

转载 作者:太空宇宙 更新时间:2023-11-03 17:49:41 26 4
gpt4 key购买 nike

我是 jQuery 的新手(请多多包涵),我正在使用 css-tricks 提供的代码片段,从导航菜单启用动画滚动到单个页面站点上的目标。

<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
}, 1000);
return false;
}
}
});
});
</script>

目前,它似乎适用于页面上对 a href="#"的任何使用,而不仅仅是导航中的目标部分。

导航html如下:

<nav>
<ul>
<li id="navwhat"><a href="#sectionwhat"><div class="navicon what"><img src="images/ah_nav_what_01.png" alt="what i do" name="navwhaticon" id="navwhaticon"></div><span>what i do</span></a></li>
<li id="navwork"><a href="#sectionwork"><div class="navicon work"><img src="images/ah_nav_work_01.png" alt="my work" name="navworkicon" id="navworkicon"></div><span>my work</span></a></li>
<li id="navexperience"><a href="#sectionexperience"><div class="navicon experience"><img src="images/ah_nav_experience_01.png" alt="my experience" name="navexperienceicon" id="navexperienceicon"></div><span>my experience</span></a></li>
<li id="navabout"><a href="#sectionabout"><div class="navicon about"><img src="images/ah_nav_about_01.png" alt="about me" name="navabouticon" id="navabouticon"></div><span>about me</span></a></li>
<li id="navcontact"><a href="#sectioncontact"><div class="navicon contact"><img src="images/ah_nav_contact_01.png" alt="contact me" name="navcontacticon" id="navcontacticon"></div><span>contact me</span></a></li>
<li id="navfind"><a href="#sectionfind"><div class="navicon find"><img src="images/ah_nav_find_01.png" alt="find me" name="navfindicon" id="navfindicon"></div><span>find me</span></a></li>
</ul>
</nav>

如何将功能限制在导航目标上?

我是否在 jQuery 中单独指定每个部分的 div?

我是否将一个类应用于目标部分并在函数中指定该类?

该功能是否只能应用于导航 div 中的链接?

非常感谢任何和所有建议。

最佳答案

只需将 nav 添加到选择器 -> $('nav a[href*=#]:not([href=#])') 仅定位导航元素内的 anchor

$(function () {
$('nav 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
}, 1000);
return false;
}
}
});
});

关于jQuery 动画滚动 : Can I limit the function to specific targets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27530287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com