gpt4 book ai didi

jquery - addClass 到 li smoothscroll this.hash

转载 作者:行者123 更新时间:2023-11-28 01:47:58 24 4
gpt4 key购买 nike

我在页面上有一些散列链接,我试图在单击链接后添加一个类。

我拥有的 smoothScroll 运行良好,甚至可以添加类,但它会将类添加到每个 li 元素。我如何定位选定的 hash li 元素并仅向该元素添加一个类。

$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
$('#subNavMain li').addClass('active');
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
console.log(target);
};
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ul>
<li><a href="#top-review-expressVPN1">#1 - ExpressVPN <span class="badge">10/10</span></a></li>
<li><a href="#top-review-expressVPN2">#2 - ExpressVPN <span class="badge">9/10</span></a></li>
</ul>

最佳答案

只需将类添加到 $(this) 即可,该类是在 .click() 函数中传递的对象。例如:

$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
$(this).addClass('active');
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
console.log(target);
};
});
}
}
});

关于jquery - addClass 到 li smoothscroll this.hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50101258/

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