JavaScript實(shí)現(xiàn)修改偽類樣式
項(xiàng)目中時(shí)常會(huì)需要用到使用JavaScript來(lái)動(dòng)態(tài)控制為元素(:before,:after)的樣式,但是我們都知道JavaScript或jQuery并沒(méi)有偽類選擇器。這里總結(jié)一下幾種常見(jiàn)的方法。
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>中動(dòng)態(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()動(dòng)態(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 引入了另一個(gè) Java 運(yùn)算符 instanceof 來(lái)解決這個(gè)問(wèn)題。instanceof 運(yùn)算符與 typeof 運(yùn)算符相似,用于識(shí)別正在處理的對(duì)象的類型。,需要的朋友可以參考下2019-06-06
javascript實(shí)現(xiàn)英文首字母大寫(xiě)
本文給大家總結(jié)了幾種可以實(shí)現(xiàn)英文首字母大寫(xiě)的javascript腳本,另附上一個(gè)CSS的實(shí)現(xiàn)方法,非常的簡(jiǎ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中通常把這個(gè)擁有者叫做執(zhí)行上下文。2010-07-07
玩轉(zhuǎn)JavaScript OOP - 類的實(shí)現(xiàn)詳解
下面小編就為大家?guī)?lái)一篇玩轉(zhuǎn)JavaScript OOP - 類的實(shí)現(xiàn)詳解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06
window.open的頁(yè)面如何刷新(父頁(yè)面)上層頁(yè)面
在開(kāi)發(fā)過(guò)程中會(huì)經(jīng)常遇到window.open打開(kāi)的頁(yè)面,同時(shí)問(wèn)題出現(xiàn)了如何刷新上層頁(yè)面呢?本文將詳細(xì)介紹,需要了解的朋友可以參考下2012-12-12
Javascript實(shí)現(xiàn)飛動(dòng)廣告效果的方法
這篇文章主要介紹了Javascript實(shí)現(xiàn)飛動(dòng)廣告效果的方法,可實(shí)現(xiàn)廣告窗口的浮動(dòng)顯示效果,且廣告窗口具有關(guān)閉功能,需要的朋友可以參考下2015-05-05
小程序使用watch監(jiān)聽(tīng)數(shù)據(jù)變化的方法詳解
這篇文章主要介紹了小程序使用watch監(jiān)聽(tīng)數(shù)據(jù)變化的方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09

