CSS style for links pointing to the current page?

人盡茶涼 提交于 2020-01-13 01:29:28

问题


I was wondering if there is any way in CSS3 to style links pointing to the same page that are already displayed in the browser—for example to highlight it red in the navigation telling the user "You are here right now!" since I have few lists with links, and I expect some users will probably read them one-by-one.

So if the browser is at /features/feature3.php, then obviously I would like to change the appearance of all links with the same href destination.

It seems like there is only :hover, :focus, and :active, but nothing to solve this problem purely in CSS. Am I missing something?


回答1:


you can use CSS3 attribute selectors for this.

a[href='your url'] { *** }



回答2:


Try for this Example, good enough helpfull.

<ul id="navlist">
   <li><a href="index.html" id="homenav">Home</a></li>
   <li><a href="products.html" id="prodnav">Products</a></li>
   <li><a href="faq.html" id="faqnav">FAQ</a></li>
   <li><a href="contact.html" id="connav">contact us</a></li>
</ul>

<body id="home">

body#home a#homenav,
body#products a#prodnav,
body#faq a#faqnav,
body#contact a#connav {
   color: #fff;
   background: #930;
}



回答3:


So CSS doesn't currently have this functionality directly supported. Thus you have to look for alternatives and weigh the trade-offs.

Use JavaScript and jQuery to add a class

$(function () {
  $('a[href="' + document.location.pathname + '"]').addClass("current");
});

Then you can base your styles around the .current selector.

a.current {background-color: white;}

Just don't put class="current" in your HTML - let them all be normal when the page loads and the javascript will add the class to the correct element(s). This is nice because it will work for any page and doesn't require dynamic code on the server. Of course this can be done without jQuery as well. This may need adjustment for query string parameters, absolute URLs, and a few other edge cases, but works fine for the straightforward case.

Use dynamic code on the server side to put class="current" on the proper elements

You could do it this way as well but it won't be quite as concise and expressive as the JavaScript version because most server side programming environments don't have the nice DOM selectors available.



来源:https://stackoverflow.com/questions/8998574/css-style-for-links-pointing-to-the-current-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!