从javascript更改伪元素样式

时间:2018-03-05 08:20:49

标签: javascript css dom pseudo-element

如何更改伪元素样式的CSS?

我正在尝试获取CSS before::规则并将left:更改为95%4px。 我怎样才能在我的背景下执行此操作?

我也使用document.querySelector进行了一些测试,但它不起作用,我得到一个计算只读错误。

你有什么建议吗?

  

示例:

的CSS

.iziToast-wrapper-bottomLeft .iziToast.iziToast-balloon:before {
  border-right: 15px solid transparent;
  border-left: 0 solid transparent;
  right: auto;
  left: 8px;
}

JS

    if(description_iziToast){
        let RightMode = event.x>window.innerWidth/2;
        let bubblePosition = document.getElementsByClassName("iziToast-balloon")[0]; // get the div that hold the bubble
        let ajustScreenLR = RightMode && document.getElementsByClassName("iziToast")[0].offsetWidth || 0; // halfScreen ajustement
        //bubblePosition.style.left = RightMode && '95%' || '4px'; // here i need to change the position in the befor:: attribut
        description_iziToast.style.left = `${event.x-20-ajustScreenLR}px`; 
        description_iziToast.style.top = `${event.y-105}px`;
    }
    }else{
        if(description_iziToast){ iziToast.destroy(); description_iziToast = false; };
    }

此处为app console debug

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:4)

由于DOM中不存在伪元素,因此无法在Javascript中访问它们。 解决方法是创建<span>而不是使用:before,并且必须应用相同的逻辑。

答案 1 :(得分:4)

以下是两种直接操作伪元素的方法:

第一种方式是使用某种风格管理器 这位&#34;经理&#34;是一个方法的对象,允许在运行中更容易地处理CSS规则,所以这是一个非常基本的例子,您可以根据您的特定需求进行研究和实现:

&#13;
&#13;
var elm = document.querySelector('main');

// Reference: https://stackoverflow.com/a/28930990/104380
var styleManager = (function() {
    // Create the <style> tag
    var style = document.createElement("style")

    // WebKit hack
    style.appendChild(document.createTextNode(""));

    // Add the <style> element to the page
    document.head.appendChild(style);
    
    function getStyleRuleIndexBySelector(selector, prop){
      var result = [], i,
          value = (prop ? selector + "{" + prop + "}" : selector).replace(/\s/g, ''), // remove whitespaces
          s = prop ? "cssText" : "selectorText";

      for( i=0; i < style.sheet.cssRules.length; i++ )
        if( style.sheet.cssRules[i][s].replace(/\s/g, '') == value)
          result.push(i);

      return result;
    };

    return {
      style : style,
      
      getStyleRuleIndexBySelector : getStyleRuleIndexBySelector,
      
      add(prop, value){
        return style.sheet.insertRule(`${prop}{${value}}`, style.sheet.cssRules.length);
      },
      
      remove(selector, prop){
        var indexes = getStyleRuleIndexBySelector(selector, prop), i = indexes.length;
        
        // reversed iteration so indexes won't change after deletion for each iteration
        for( ; i-- ; )
          style.sheet.deleteRule( indexes[i] );
      }
    }
})();


elm.addEventListener('mouseenter', function(){
   // each new rule should be added the END of the sheet
   styleManager.add('main::before','left:90%; top:60%;');
   styleManager.add('main::before','left:70%;');
});

elm.addEventListener('mouseleave', function(){
  styleManager.remove('main::before', 'left:70%;');  // you can also try without the "left:70%;" part
});
&#13;
main{  
  position:relative;
  width: 200px;
  height: 200px;
  border: 1px dashed silver;
}

main::before{
  content: 'pseudo';
  width: 100px;
  height: 100px;
  background: lightgreen;
  position: absolute;
  left: 10px;
  top: 40px;
  
  transition:.3s ease-out;
}
&#13;
<main>Hover &amp; out</main>
&#13;
&#13;
&#13;

另一种方式 - 使用CSS变量:

&#13;
&#13;
var elm = document.querySelector('main');

elm.addEventListener('mouseenter', function(){
   elm.style.setProperty('--before-left', '90%');
});

elm.addEventListener('mouseleave', function(){
  elm.style.setProperty('--before-left', '10px');
});
&#13;
main{  
  --before-left : 10px; /* <-- Your CSS should use variables for this to work */
  
  position:relative;
  width: 200px;
  height: 200px;
  border: 1px dashed silver;
}

main::before{
  content: 'pseudo';
  width: 100px;
  height: 100px;
  background: lightgreen;
  position: absolute;
  left: var(--before-left); /* <-- using the variable */
  top: 40px;

  transition:.3s ease-out;
}
&#13;
<main>Hover &amp; out</main>
&#13;
&#13;
&#13;