根据 CSS 类名设置背景颜色 [英] Set background color based on a CSS class name

查看:55
本文介绍了根据 CSS 类名设置背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些不同的 div 元素,其中包含 redgreen 之类的类.

我想将 div 元素的背景颜色设置为其类名.所以如果类名是 red,我希望 div 背景是红色的.我不确定是否需要添加 javascript 或其他内容.我看过这个 而这根本不是我想要的.

提前致谢!

解决方案

动态且不依赖于类名的解决方案是使用自定义 数据属性.

看看下面的解决方案:

<脚本>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 类名设置背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆