href 不以“#”结尾的锚点的 CSS 选择器

CSS Selector for anchor with href not ending in '#'

本文关键字:CSS 选择器 结尾 不以 href      更新时间:2023-09-26

我想在页面加载时显示一个加载图标。

我正在使用HTML,CSS和JS代码。

.HTML:

<div class="loader-icon"></div>

.JS:

$(window).load(function() {
    $(".loader-icon").fadeOut("slow");
});
$('a').click(function(){
    $(".loader-icon").fadeIn("slow");
})

和一些 CSS 显示div.loader-icon的加载图标。

如果我单击任何重定向到另一个页面的链接,它工作正常。但是当链接没有重定向到另一个页面时,它不起作用。就像我单击"返回顶部"图标一样,加载图标一直显示。它不会淡出。

假设:

<a href="http://example.com/page/">Page Now</a>
<a href="http://example.com/page/#">Back to Top</a>
<a href="http://example.com/page2/">Page Other</a>

它适用于"页面其他",但不适用于"返回顶部"。

所以我想为href不以'#'结尾的锚选择一个选择器。或者有没有更好的方法使用不同的简单技巧来做同样的事情?

您是否需要担心其他网址,包括#?如果没有,您可以在此选择器上执行绑定:

a:not([href*='#'])

这只会定位网址中不包含 # 的链接。你也可以使用这个

a:not([href^='#'])

定位任何不以 # 开头的链接,以及

a:not([href$='#'])

对于不以 # 结尾的任何链接。希望这些帮助之一!

您可以将 end with 选择器与 not()

一起使用

 $('a').not('[href$="#"]').on("click", function(e) {
   $(this).toggleClass("active");
   e.preventDefault();
 });
.active{ background-color: lime; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#">Has # at end</a>
<a href="http://www.google.com">FOO</a>
<a href="http://www.google.com">BAR</a>

可以使用 :not() 选择器,但引用 jQuery 的建议:

.not() 方法最终将为您提供比将复杂选择器或变量推送到 :not() 选择器过滤器中更具可读性的选择。在大多数情况下,这是一个更好的选择。

它不起作用,因为您要添加窗口加载时的事件,这意味着如果您希望图标淡出,则需要刷新页面。

当您单击返回顶部链接时,也会添加事件。

<a href="http://example.com/page/#" onclick="myFunct();">Back to Top</a>
...
function myFunct(){
$(".loader-icon").fadeOut("slow");
}