JavaScript實(shí)現(xiàn)修改偽類樣式
項(xiàng)目中時常會需要用到使用JavaScript來動態(tài)控制為元素(:before,:after)的樣式,但是我們都知道JavaScript或jQuery并沒有偽類選擇器。這里總結(jié)一下幾種常見的方法。
HTML
<p class="red">Hi, this is a plain-old, sad-looking paragraph tag.</p>
CSS
.red::before {
content: 'red';
color: red;
}
方法一
使用JavaScript或者jQuery切換<p>元素的類名,修改樣式。
.green::before {
content: 'green';
color: green;
}
$('p').removeClass('red').addClass('green');
方法二
在已存在的<style>中動態(tài)插入新樣式。
document.styleSheets[0].addRule('.red::before','color: green');
document.styleSheets[0].insertRule('.red::before { color: green }', 0);
方法三
創(chuàng)建一份新的樣式表,并使用JavaScript或jQuery將其插入到<head>中
// Create a new style tag
var style = document.createElement("style");
// Append the style tag to head
document.head.appendChild(style);
// Grab the stylesheet object
sheet = style.sheet
// Use addRule or insertRule to inject styles
sheet.addRule('.red::before','color: green');
sheet.insertRule('.red::before { color: green }', 0);
jQuery
$('<style>.red::before{color:green}</style>').appendTo('head');
方法四
使用HTML5的data-屬性,在屬性中使用attr()動態(tài)修改。
<p class="red" data-attr="red">Hi, this is plain-old, sad-looking paragraph tag.</p>
.red::before {
content: attr(data-attr);
color: red;
}
$('.red').attr('data-attr', 'green');
以上就是我們?yōu)榇蠹艺淼乃姆N方法,如果大家有更好的方法,可以在下方的留言區(qū)討論。
相關(guān)文章
深入剖析JavaScript instanceof 運(yùn)算符
這篇文章主要介紹了深入剖析JavaScript instanceof 運(yùn)算符,ECMAScript 引入了另一個 Java 運(yùn)算符 instanceof 來解決這個問題。instanceof 運(yùn)算符與 typeof 運(yùn)算符相似,用于識別正在處理的對象的類型。,需要的朋友可以參考下2019-06-06
javascript實(shí)現(xiàn)英文首字母大寫
本文給大家總結(jié)了幾種可以實(shí)現(xiàn)英文首字母大寫的javascript腳本,另附上一個CSS的實(shí)現(xiàn)方法,非常的簡單實(shí)用,這里推薦給大家,有需要的小伙伴可以參考下。2015-04-04
JavaScript實(shí)現(xiàn)Java中StringBuffer的方法
這篇文章主要介紹了JavaScript實(shí)現(xiàn)Java中StringBuffer的方法,實(shí)例分析了StringBuffer類的實(shí)現(xiàn)與使用技巧,需要的朋友可以參考下2015-02-02
this和執(zhí)行上下文實(shí)現(xiàn)代碼
Javascript中this關(guān)鍵字通常指向當(dāng)前函數(shù)的擁有者。在javascript中通常把這個擁有者叫做執(zhí)行上下文。2010-07-07
玩轉(zhuǎn)JavaScript OOP - 類的實(shí)現(xiàn)詳解
下面小編就為大家?guī)硪黄孓D(zhuǎn)JavaScript OOP - 類的實(shí)現(xiàn)詳解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06
Javascript實(shí)現(xiàn)飛動廣告效果的方法
這篇文章主要介紹了Javascript實(shí)現(xiàn)飛動廣告效果的方法,可實(shí)現(xiàn)廣告窗口的浮動顯示效果,且廣告窗口具有關(guān)閉功能,需要的朋友可以參考下2015-05-05
小程序使用watch監(jiān)聽數(shù)據(jù)變化的方法詳解
這篇文章主要介紹了小程序使用watch監(jiān)聽數(shù)據(jù)變化的方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09

