首页 > 解决方案 > 在 div 中的所有元素上设置文本颜色

问题描述

我有一个看起来像这样的 SCSS-mixin:

/**
 * Text color
 */
@mixin text-color( $color ){
    color: $color;

    h1,
    h2,
    h3,
    h4,
    h5 {
        color: $color
    }

    p,
    li {
        color: $color;
    }

    a {
        color: $color;
        text-decoration: underline;

        &:hover {
            text-decoration: none;
        }
    }
}

这不是最好的东西,但它真的很方便。每当播放某些子元素的文本颜色时,我都会使用它。时不时地,有一个li或一个a从更远的树上得到一些样式。

我正在寻找 JavaScript 等价物。原因是,我希望用户选择一种十六进制颜色,然后所有元素都将获得该颜色。

我当前的版本是做这样的事情(在 Vue-mixin 中):

mounted(){
  let chosenHex = #FF0000;
  this.setTextColorOnAllElements( chosenHex );
},
methods: {
  setTextColorOnAllElements( textColor ){
    setTimeout( () => { // Otherwise the el's aren't rendered
      this.setTextColorOnTagType( textColor, 'h1' );
      this.setTextColorOnTagType( textColor, 'h2' );
      this.setTextColorOnTagType( textColor, 'h3' );
      this.setTextColorOnTagType( textColor, 'h4' );
      this.setTextColorOnTagType( textColor, 'h5' );
      this.setTextColorOnTagType( textColor, 'h6' );
      this.setTextColorOnTagType( textColor, 'h7' );
      this.setTextColorOnTagType( textColor, 'p' );
      this.setTextColorOnTagType( textColor, 'li' );
      this.setTextColorOnTagType( textColor, 'span' );
      this.setTextColorOnTagType( textColor, 'a' );
    });
  },
  setTextColorOnTagType( textColor, tagType ){
    if( this.id ){
      let elements = document.querySelectorAll( '#' + this.id + ' ' + tagType );
      elements.forEach( (element) => {
        element.style.color = textColor;
      });
    }
  }

}

它只是啰嗦,感觉笨拙。


首要问题:关于设置 div 内所有元素的文本颜色的 JavaScript 函数有什么建议吗?

标签: javascript

解决方案


在这里回答最重要的问题。

你在寻找这样的东西吗?运行代码段。

//use querySelectorAll to get all elements within the div
var children = document.querySelectorAll("div p")

//loop through those elements and change the color
for (var i = 0; i < children.length; i++) {
  children[i].style.color = "blue";
}
<div id="parent">
  <p>Lorem</p>
  <p>Ipsum</p>
  <p>Lorem</p>
  <p>Ipsum</p>
  <p>Lorem</p>
  <p>Ipsum</p>
  <p>Lorem</p>
  <p>Ipsum</p>
</div>

或者,定位父 div 以使其更容易:

//use querySelector to target parent div
var parent = document.querySelector("div");

//set color on parent div to change color of children
parent.style.color = "blue";
<div id="parent">
  <h1>Lorem</h1>
  <h2>Ipsum</h2>
  <h3>Lorem</h3>
  <span>Ipsum</span>
  <li>Lorem</li>
</div>


推荐阅读