jquery - addClass to li smoothscroll this.hash
问题描述
我在页面上有一些散列链接,我试图在单击链接后添加一个类。
我拥有的 smoothScroll 工作得很好,甚至添加了类,但它把类添加到了每个 li 元素。我如何定位选定的哈希 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);
};
});
}
}
});
推荐阅读
- macos - `appdmg` 工具在 Mac OSX 10.15 中经常失败
- keras - 当目标是高斯标签时,最好的损失函数可能是什么?
- api - 无法在本地以及带有 IIS 的服务器上运行我的 .net 核心应用程序
- php - Wordpress - 将 wp_redirect url 更改为动态链接
- selenium - 在日历中设置天数路径时返回多个值
- java - 使用方法而不是 @annotation 的 Spring AOP 建议:为什么?
- mysql - 当 useInformationSchema 为真时,为什么 tinyint(1) 不被视为布尔值?
- react-native - 流程如何与本机反应和选项'all = true'一起使用?
- c# - 如何在调试应用程序时打开/编辑/保护本地 app.config 文件?
- delphi - Delphi cxGrid 如何防止在移动列时创建第二行标题?