如何从 JS 获取 header-section:before 进行样式设置

How to reach for the header-section:before from the JS for styling

我想根据值更改 header-section:before 中的背景颜色。

这是html部分

<section class="header-section" id="main-header"> 
    <div class="content">
        <div class="header"> 
            <h1>
                <span id="temperature"></span>
                <span id="todays-img"></span>
            </h1>
        </div>
        <h2><span id="city-name"></span></h2>
        <p><span id="description"></span></p>
        <div class="sunrise-sunset">
            <p class="sun-child"><span id="sunrise"></span></p>
            <p class="sun-child"><span id="sunset"></span></p>
        </div>
    </div>
</section>

在css中背景色定义如下:

.header-section:before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 90%;
    background: linear-gradient(45deg, #8AB7F8, #D6E4F9);
    border-radius: 0 0 50% 50%/0 0 50% 50%;
    transform: scalex(1.5);
}

这就是我在 JS 中所拥有的,它改变了 header-section 的颜色,但没有改变 header-section:before

    const headerBackground = document.getElementById('main-header');

    const checkTemperature = () => {
      if (filteredForecast[0].main.temp < 0) {
        headerBackground.style.backgroundColor = '#BDCBF5';
      }

所以现在它正在改变 header-section 的颜色,而不是 header-section:before。我如何才能在 JS 中获取 header-section:before 因为我无法通过 document.getElementById.

从 html 获取它

不能直接改变伪元素的样式。更改它的唯一方法是检索样式表并更改相关规则。这是一个片段,可以作为进一步编写脚本的基础(删除 html 以显示 minimum reproducable example)。请注意,在初始 css 中, background 属性 设置为 'black'.

同时检查 this JsFiddle

// find the stylesheet (in the SO context, it's the first stylesheet)
const styleElem = document.styleSheets[0];

// be conservative, check everything
if (styleElem) {
  // retrieve the rules of the stylesheet
  const ruleSet = styleElem.cssRules ? styleElem.cssRules : styleElem.rules;
  
  if (ruleSet) {
    // retrieve the .header-section:before rule
    const headerSectionRule = [...ruleSet].find(rule => 
      rule.selectorText.startsWith(".header-section::before"));
      //                                           ^ note '::'

    if (headerSectionRule && headerSectionRule.style) {
      // found the rule, now set the background style
      headerSectionRule.style.background = 
        "linear-gradient(45deg, #8AB7F8, #D6E4F9)";
    }
  }
}
.header-section:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 90%;
  /* Note: initially black */
  background: #000;
  border-radius: 0 0 50% 50%/0 0 50% 50%;
  transform: scalex(1.5);
}
<section class="header-section" id="main-header">
<!-- removed for simplicity -->
</section>