首頁  >  文章  >  web前端  >  給before和after偽元素設定js效果的方法_javascript技巧

給before和after偽元素設定js效果的方法_javascript技巧

WBOY
WBOY原創
2016-05-16 15:27:471547瀏覽

層疊樣式表(CSS)的主要目的是為HTML元素添加樣式,然而,在某些案例中為文件添加額外的元素是多餘的或是不可能的。事實上CSS中有一個特性允許我們添加額外元素而不擾亂文件本身,這就是「偽元素」。

前面的話

   無法直接為before和after偽元素設定js效果 

範例說明

  現在需要為(id為box,內容為"我是測試內容"的div)添加(:before內容為"前綴",顏色為紅色的偽類)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="box">我是测试内容</div>  <script>    var oBox = document.getElementById('box');  </script>
</body>
</html> 

解決方法

【方法一】動態嵌入CSS樣式

  IE8-瀏覽器將

<script>
function loadStyleString(css){
  var style = document.createElement("style");
  style.type = "text/css";
  try{
    style.appendChild(document.createTextNode(css));
  }catch(ex){
    style.styleSheet.cssText = css;
  }
  var head = document.getElementsByTagName('head')[0];
  head.appendChild(style);
}
loadStyleString("#box:before{content:'前缀';color: red;}");
<script> 

【方法二】加上自帶偽類的類別名稱

<style>
  .change:before{content: "前缀";color: red;}
</style> 
<script>
  oBox.className = 'change';
</script> 

  [缺點]此方法無法控制偽元素裡面的content屬性的值

【方法三】利用setAttribute實作自訂content內容

<style>
  .change:before{content: attr(data-beforeData);color: red;}
</style> 
<script>
  oBox.setAttribute('data-beforeData','前缀');
</script> 

  [注意]此方法只可用setAttribute實現,經測試用dataset方法無效

【方法四】新增樣式表

  firefox瀏覽器不支援addRule()方法,IE8-瀏覽器不支援insertRule()方法。相容寫法如下:

<script>
  function insertRule(sheet,ruleKey,ruleValue,index){
    return sheet.insertRule &#63; sheet.insertRule(ruleKey+ '{' + ruleValue + '}',index) : sheet.addRule(ruleKey,ruleValue,index);
  } 
  insertRule(document.styleSheets[0],'#box:before','content:"前缀";color: red;',0)  
</script> 

  [缺點]此方法必須有內部

【方法五】修改樣式表

  先使用方法四新增空的樣式表,然後取得新產生的

<script>
function loadStyleString(css){
  var style = document.createElement("style");
  style.type = "text/css";
  try{
    style.appendChild(document.createTextNode(css));
  }catch(ex){
    style.styleSheet.cssText = css;
  }
  var head = document.getElementsByTagName('head')[0];
  head.appendChild(style);
}
loadStyleString('');
document.head.getElementsByTagName('style')[1].innerHTML = "#oBox:before{color: " + colorValue + ";}";
</script> 

  [注意]只能使用getElementsByTagName('style')[1]的方法,經測驗使用stylesheets[1]方法無效

DEMO

    點選下列對應屬性值可進行演示

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn