javascript - 在 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 函数有什么建议吗?
解决方案
在这里回答最重要的问题。
你在寻找这样的东西吗?运行代码段。
//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>
推荐阅读
- cassandra - 如何为 CQLSH 中的任何列运行 SELECT DISTINCT?
- spring - 如何使用 Spring Boot 和 Maven 设置单独的单元测试框架
- java - 蓝牙 LeScan 没有达到目标
- angular - Angular 6 - httpClient 发布 XML 文件
- spring-boot - Spring Boot 2.0 WebClient 在继续之前处理 404
- javascript - 在元素中查找行,然后用标签包装它
- javascript - 如何计算 CheckSum 8 Xor
- macos - C++:无法读取 macOS 包中的资源文件
- python-3.6 - 将 Vertica 连接为 Django 后端
- android - MediaStore.ACTION_VIDEO_CAPTURE 从 Nohat 设备上的预览屏幕播放录制的视频时应用程序崩溃