简体   繁体   中英

How to use aria-expanded=“true” to change a css property

I want to use aria-expanded="true" to change a css property like an active class :

<li class="active">
   <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> 
       <span class="network-name">Google+</span>
   </a>
</li>

I want the <a> to background-color: #42DCA3 but only when aria-expanded="true" .

Why javascript when you can use just css?

 a[aria-expanded="true"]{ background-color: #42DCA3; }
 <li class="active"> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="network-name">Google+</span> </a> </li> <li class="active"> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> <span class="network-name">Google+</span> </a> </li>

 li a[aria-expanded="true"] span{ color: red; }
 <li class="active"> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="network-name">Google+</span> </a> </li> <li class="active"> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> <span class="network-name">Google+</span> </a> </li>

 li a[aria-expanded="true"]{ background: yellow; }
 <li class="active"> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="network-name">Google+</span> </a> </li> <li class="active"> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> <span class="network-name">Google+</span> </a> </li>

If you were open to using JQuery, you could modify the background color for any link that has the property aria-expanded set to true by doing the following...

$("a[aria-expanded='true']").css("background-color", "#42DCA3");

Depending on how specific you want to be regarding which links this applies to, you may have to slightly modify your selector.

You could use querySelector() with attribute selector '[attribute="value"]' , then affect css rule using .style , as you can see in the example below:

 document.querySelector('a[aria-expanded="true"]').style.backgroundColor = "#42DCA3";
 <ul><li class="active"> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="network-name">Google+ with aria expanded true</span></a> </li> <li> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> <span class="network-name">Google+ with aria expanded false</span></a> </li> </ul>

jQuery solution :

If you want to use a jQuery solution you could simply use css() method :

$('a[aria-expanded="true"]').css('background-color','#42DCA3');

Hope this helps.

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