问题描述
我有这些不同的 div 元素,其中包含 red
或 green
之类的类.
<div class="color_box red"></div><div class="color_box orange"></div><div class="color_box Yellow"></div><div class="color_box green"></div><div class="color_box blue"></div><div class="color_box Purple"></div><div class="color_box black"></div><div class="color_box white"></div>
我想将 div 元素的背景颜色设置为其类名.所以如果类名是 red
,我希望 div 背景是红色的.我不确定是否需要添加 javascript 或其他内容.我看过这个 而这根本不是我想要的.
提前致谢!
动态且不依赖于类名的解决方案是使用自定义 数据属性.
看看下面的解决方案:
<div data-backgroundcolor="red" class="color_box">BOX</div><div data-backgroundcolor="orange" class="color_box">BOX</div><div data-backgroundcolor="yellow" class="color_box">BOX</div><div data-backgroundcolor="green" class="color_box">BOX</div><div data-backgroundcolor="blue" class="color_box">BOX</div><div data-backgroundcolor="purple" class="color_box">BOX</div><div data-backgroundcolor="black" class="color_box">BOX</div><div data-backgroundcolor="white" class="color_box">BOX</div><脚本>const colorboxes = document.querySelectorAll('.color_box');colorboxes.forEach(el => {el.style.backgroundColor = el.dataset.backgroundcolor})</script>
I have these different div elements with classes such as red
or green
.
<div class="sidebar">
<div class="color_box red"></div>
<div class="color_box orange"></div>
<div class="color_box yellow"></div>
<div class="color_box green"></div>
<div class="color_box blue"></div>
<div class="color_box purple"></div>
<div class="color_box black"></div>
<div class="color_box white"></div>
</div>
I want to set the background color of the div element to its class name. So if the class name is red
, I would want the div background to be red. I'm not sure if I need to add javascript or something else. I've looked at this and it was not what I wanted at all.
Thank you in advance!
A solution that is dynamic and does not depend on class names is the use of a custom data attribute.
Take a look at the following solution:
<div class="sidebar">
<div data-backgroundcolor="red" class="color_box">BOX</div>
<div data-backgroundcolor="orange" class="color_box">BOX</div>
<div data-backgroundcolor="yellow" class="color_box">BOX</div>
<div data-backgroundcolor="green" class="color_box">BOX</div>
<div data-backgroundcolor="blue" class="color_box">BOX</div>
<div data-backgroundcolor="purple" class="color_box">BOX</div>
<div data-backgroundcolor="black" class="color_box">BOX</div>
<div data-backgroundcolor="white" class="color_box">BOX</div>
</div>
<script>
const colorboxes = document.querySelectorAll('.color_box');
colorboxes.forEach(el => {
el.style.backgroundColor = el.dataset.backgroundcolor
})
</script>
这篇关于根据 CSS 类名设置背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!