[英]JQuery Smooth Scroll - How to not target one anchor link?
我正在使用以下Jquery来平滑滚动页面上的锚链接。 我有一个我不希望定位的链接-有一种方法可以编辑代码以定位除一个锚定链接以外的所有链接?
我也复制了下面的链接。
var $root = $('html, body');
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
这是我不想被称为的链接:
<a href="#" class="cn-set-cookie button wp-default">Ok</a>
这些是我确实想通过函数调用的链接:
<li class="key-details"><a href="#key-details-scroll">Key Information</a></li>
<li class="about"><a href="#about">About the Service</a></li>
<li class="health"><a href="#health-experience">Health Experience</a></li>
给它上课...说“ no_smooth”。
<a href="#" class="cn-set-cookie button wp-default no_smooth">Ok</a>
然后使用:not()
排除它。
$(document).on('click', 'a[href^="#"]:not(".no_smooth")', function (event) {
//... Rest unchanged
});
解决方案 1:
var $root = $('html, body');
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
if($(this).hasClass('wp-default')) return;// with this line of code you'll prevent to call function on "OK" anchor
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
解决方案 2:
或者,您可以通过以下方式修改代码:
var $root = $('html, body');
$(document).on('click', 'a[href^="#"]:not(".wp-default")', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
解决方案 3:
另一种方法是对href
使用其他属性:
<a href="javascript:void(0);" class="cn-set-cookie button wp-default">Ok</a>
javascript:void(0);
将阻止此锚调用任何js函数。
PS :您可以使用此类名称以及cn-set-cookie
代替wp-default
也可以将类设置为那些您不想使它们调用的滚动平滑的锚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.