如何使用html和javascript中的输入更改多个id颜色

问题描述 投票:2回答:1

我有一个网页,当输入静音或静音文本时,我想通过远程或触摸屏来对其进行操作。这是我当前拥有的代码,如果调用togglemute()静音子将变为红色,并且如果静音将变为绿色。我想知道如何将其与要在底部操作的html代码合并,以便在输入文本静音或静音文本时id =“ text”和id =“ text1”更改颜色。请指教。谢谢!

HTML:

<div class="mute-container">
    <div class="mute-on">Mute On</div>
    <div class="mute-off">Mute Off</div>
</div>

JavaScript:

function toggleMute() {
    document.querySelector('.mute-container').classList.toggle('on');
}

CSS:

.mute-container.on .mute-on {
    color: red;
}

.mute-container:not(.on) .mute-off {
    color: green;
}

要处理/合并的HTML:

<h1 class="l1-txt1 txt-center p-t-0 p-b-10">
    <p id="text1" style="color:white; font-weight: 600"></p>
</h1>

<h1 class="l1-txt1 txt-center p-t-0 p-b-60">
    <p id="text" style="color:crimson; font-weight: 600"></p>
</h1>
javascript html css telnet
1个回答
0
投票

比方说,您希望text1对应于mute-on的行为,即,在启用时将red设为打开,而text的行为与mute-off相似,即在启用时变为green(切换如有必要)。我还将假设您希望根据内置CSS将text1的切换颜色设置为white,将text的切换颜色设置为crimson

然后这是一个简单的方法:

a)在下面的HTML代码周围添加一个容器元素,并为其指定类mute-container。像这样:

<div class="mute-container">

    <h1 class="l1-txt1 txt-center p-t-0 p-b-10">
        <p id="text1" style="color:white; font-weight: 600"></p>
    </h1>

    <h1 class="l1-txt1 txt-center p-t-0 p-b-60">
        <p id="text" style="color:crimson; font-weight: 600"></p>
    </h1>

</div>

b)将类mute-onmute-off添加到ID为text1text的元素中:

<div class="mute-container">

    <h1 class="l1-txt1 txt-center p-t-0 p-b-10">
        <p id="text1" class="mute-on" style="color:white; font-weight: 600"></p>
    </h1>

    <h1 class="l1-txt1 txt-center p-t-0 p-b-60">
        <p id="text" class="mute-off" style="color:crimson; font-weight: 600"></p>
    </h1>

</div>

c)最后,为了使默认颜色定义的内联(whitecrimson)不覆盖已切换的颜色(redgreen),请使用

  • 向您添加!important;非内嵌CSS规则:

    .mute-container.on .mute-on {
        color: red !important;
    }
    
    .mute-container:not(.on) .mute-off {
        color: green !important;
    }
    

  • 将默认颜色的内联CSS移入非内联CSS(并以内联方式删除它们:

    .mute-container .mute-on { /* text1 - will turn red when toggled on */
        color: white;
    }
    
    .mute-container .mute-off { /* text - will turn green when toggled on */
        color: crimson; 
    }
    

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.