[英]Unique anchor links with jQuery
I have some jQuery
code that targets all anchor links that are clicked. 我有一些针对所有单击的锚链接的jQuery
代码。
<a href="contact-us.php#media">Media Enquiries</a>
<a href="#testimonials" class="btn">See Why</a>
Jquery code jQuery代码
$('a[href*=#]').on('click', function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
However if the link is another page "contact-us.php#media" it does not work because it is expecting it to be the same page. 但是,如果链接是另一个页面“ contact-us.php#media”,则该链接不起作用,因为它期望它是同一页面。
How can I change the code to still target all # links but ignore it if it is linking to another page? 如何更改代码以仍然以所有#个链接为目标,但是如果它链接到另一个页面,则忽略它?
If href
attribute of the all target elements start with #
then you can use the Attribute Starts With selector. 如果所有目标元素的href
属性都以#
开头,则可以使用Attributes Froms选择器。
$('a[href^=#]')
Another option is checking the pathname of anchors: 另一个选项是检查锚的路径名:
$('a[href*=#]').filter(function() {
return this.pathname === location.pathname;
}).on('click', ...);
The above snippet just checks the pathname, if you want to check the hostnames as well, you can add another condition to the filter method, ie: && this.hostname === location.hostname
上面的代码片段仅检查路径名,如果您还想检查主机名,则可以在过滤器方法中添加另一个条件,即: && this.hostname === location.hostname
Found this that specifically targets the same page. 找到专门针对同一页面的内容。
Performs a smooth page scroll to an anchor on the same page 执行平滑的页面滚动到同一页面上的锚点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.