如何为被文本包围的链接添加下划线?



我需要在悬停时为被文本包围的锚链接添加下划线。

我正在寻找类似于下面的结果,但没有针对来自 id 或类的任何链接,因为它对所有链接都是相同的。

如何使用css(如果没有,则为被文本包围的链接添加下划线) 可能吗?

a{
text-decoration: none;
}
a#withText:hover{
text-decoration: underline; 
}
<span> <a href="#"> Alone link </a> <span>
<br/>
<span> Text around <a id="withText" href="#"> Text surrounded link </a> Text around </span>

您可以使用span > a:hover这将针对作为span的直接子级的所有a

a{
text-decoration: none;
}
span > a:hover{
text-decoration: underline; 
}
<a href="#"> Alone link </a>
<br/>
<span> Text around <a id="withText" href="#"> Text surrounded link </a> Text around </span>

如果你的a总是在span内,你可以像这样定位它:

span a:hover {
text-decoration: underline; 
}

这针对span内的所有a

据我所知,没有办法在css选择器中处理纯"文本节点"。我会去 JS,在那里您可以轻松检查链接的文本是否等于其父元素的所有文本。

这是一个使用jquery的小提琴,但你也可以用普通的javascript来完成。

$("a").each(function(){
if($(this).text().trim() == $(this).parent().text().trim()){
//This link is the only content of parent item, so...
$(this).addClass('no-underline');
}
});
a{text-decoration:none}
a:hover{text-decoration:underline}
a.no-underline:hover{text-decoration:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>text arround <a href="#here">the link</a></p>
<p>text arround <a href="#here">the link</a> on both side</p>
<p><a href="#here">the link</a> with text after it</p>
<p> <a href="#here">a link alone (whitespaces arround)</a> </p>

最新更新