简体   繁体   中英

How to underline links which are surrounded by text?

I need to underline anchor links which are surrounded by text on hover.

I am looking for a result similar to below but without targeting any links from id's or classes because it would be same for all the links.

How can I put underline for the links which are surrounded by text, using css(or javascript if not) Is it possible?

 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> 

If your a is always within a span you can target it like this:

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

This targets all a 's within a span .

You could use span > a:hover this will target all a that comes as a direct child of span .

 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> 

As far as I know there is no way to deal with pure "text nodes" in css selectors. I'd go to JS, where you can easily check if the text of the link is equal to all the text of it's parent element.

Here is a fiddle using jquery, but you can do it also in plain 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM