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

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

问题描述

我有这些具有不同类别的div元素,例如 red green .

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>

我想将div元素的背景色设置为其类名.因此,如果类名称为 red ,我希望div背景为红色.我不确定是否需要添加JavaScript或其他内容.我看过根本不是我想要的.

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.

谢谢!

推荐答案

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

A solution that is dynamic and does not depend on class names is the use of a custom data attribute.

看看以下解决方案:

<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天全站免登陆