本文介紹了使用javascript,jQuery實現修改before,after偽類的樣式,分享給大家,具體如下:
最近遇到一個需要改變:before,:after 偽類的樣式,發現css中并不能直接選擇某一個元素的:before和:after偽類元素,所以特總結了使用javascript和jQuery改變元素的:before和:after偽類樣式的方法。
類如如下的html及樣式
<p class="red">Hello,are you kain?</p>
css樣式
.red:before { content: 'red', background-color : red}1.使用javascript或者jQuery切換,增加元素的類
.green:before { content: 'green'; background-color: green;}$('p').addClass('green');2.在存在的style文檔中動態插入樣式
document.styleSheet[0].addRule('.red:before','background-color:green');document.styleSheet[0].insertRule('.red:before{background-color:green}',0);3.創建一份新的樣式表,并使用JavaScript或jQuert將其插入到中
var style = document.creatElement('style');document.head.appendChild(style);sheet = style.sheet;sheet.addRule('.red:before','background-color:green');sheet.insertRule('.red:before{background-color:green}',0);// jQuery$('<style>.red:before{background-color:green}</style>').appendTo('head');4.使用HTML5的data-屬性,在屬性中使用attr()動態修改。
在p標簽中增加data-attr="red"屬性,然后
$('red').attr('data-attr','green');以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選