使用JavaScript更改伪元素的样式

7

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

这里是应用程序控制台调试

在此输入图像描述

在此输入图像描述


1
如果只是要切换两个固定值,那么只需在元素上添加一个“rightMode”类,并在CSS中执行elem.rightMode :: before {left: 95%;} - Kaiido
我想避免在需要更新时修改原始的CSS代码。我可能会这样继续进行。 - jon
2个回答

15

由于伪元素在DOM中不存在,无法在Javascript中访问。

解决方法是创建一个<span>代替使用:before,并应用相同的逻辑。


在我的情况下,我创建了一个新类,实际上覆盖了伪元素(包括 ::before 和 ::after)。例如,如果我们想要重写颜色,则可以使用 .pseudo-update::before, .pseudo-update::after { color: #efefef },然后只需使用 JavaScript 将您的类添加到要更新的元素中 document.querySelector('.menu-btn-burger').classList.add('pseudo-update'); - Tom Danilov

12

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

1 - 使用某种 样式管理器

这个“管理器”是一个带有方法的对象,允许在运行时更轻松地操作 CSS 规则,因此这里有一个非常基本的示例,您可以学习并根据自己的需求实现:

var elm = document.querySelector('main');

// Reference: https://dev59.com/c14b5IYBdhLWcg3wlilP#28930990
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;
}
<main>Hover &amp; out</main>

2 - 使用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;
}
<main>Hover &amp; out</main>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接