国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

JavaScript實現修改偽類樣式

2024-05-06 16:41:08
字體:
來源:轉載
供稿:網友

項目中時常會需要用到使用JavaScript來動態控制為元素(:before,:after)的樣式,但是我們都知道JavaScript或jQuery并沒有偽類選擇器。這里總結一下幾種常見的方法。

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>中動態插入新樣式。

document.styleSheets[0].addRule('.red::before','color: green');document.styleSheets[0].insertRule('.red::before { color: green }', 0);

 

方法三

創建一份新的樣式表,并使用JavaScript或jQuery將其插入到<head>中

// Create a new style tagvar style = document.createElement("style");// Append the style tag to headdocument.head.appendChild(style);// Grab the stylesheet objectsheet = style.sheet// Use addRule or insertRule to inject stylessheet.addRule('.red::before','color: green');sheet.insertRule('.red::before { color: green }', 0);

 

jQuery

$('<style>.red::before{color:green}</style>').appendTo('head');

 

方法四

使用HTML5的data-屬性,在屬性中使用attr()動態修改。

<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');

 

以上就是我們為大家整理的四種方法,如果大家有更好的方法,可以在下方的留言區討論。

 

注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 博爱县| 泗水县| 华安县| 宁城县| 富裕县| 永吉县| 赣榆县| 鄢陵县| 阿克苏市| 三门县| 左云县| 荣昌县| 海宁市| 苍山县| 白玉县| 开平市| 红河县| 灵丘县| 东兰县| 西宁市| 杭州市| 肇东市| 灵宝市| 恩平市| 宁乡县| 海宁市| 敦煌市| 宁武县| 垫江县| 鄂托克旗| 丽江市| 耒阳市| 报价| 泗水县| 长葛市| 自治县| 乌拉特后旗| 织金县| 鞍山市| 根河市| 田东县|