【问题标题】:Changing pseudo-element style from javascript [duplicate]从javascript更改伪元素样式[重复]
【发布时间】:2018-08-12 20:24:17
【问题描述】:

如何为伪元素样式更改 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; };
    }

这里是应用控制台调试

【问题讨论】:

  • 如果真的只是左右两个固定值的切换,那么只需在元素上添加一个'rightMode'类,在css中做elem.rightMode::before { left: 95%;}
  • 我想避免在需要更新时修改原始 css 代码。我可能会以这种方式进行。

标签: javascript css dom pseudo-element


【解决方案1】:

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

【讨论】:

  • 在我的例子中,我创建了一个新类,它实际上覆盖了伪元素(::before 和::after)。例如,我们要重写颜色然后执行.pseudo-update::before, .pseudo-update::after { color: #efefef },然后使用JavaScript 将您的类添加到您要更新的元素document.querySelector('.menu-btn-burger').classList.add('pseudo-update');
【解决方案2】:

这里有两种直接操作伪元素的方法:

第一种方法是使用某种样式管理器。
这个“管理器”是一个带有方法的对象,可以更轻松地即时操作 CSS 规则,所以这里有一个非常基本的示例,您可以根据自己的特定需求学习和实施:

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
});
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;
}
&lt;main&gt;Hover &amp;amp; out&lt;/main&gt;

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

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');
});
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;
}
&lt;main&gt;Hover &amp;amp; out&lt;/main&gt;

【讨论】:

    猜你喜欢
    • 2011-05-27
    • 2014-01-28
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多