首页 > 解决方案 > 如何使用 html 和 javascript 中的输入更改多个 id 颜色

问题描述

我有一个网页,我想在输入静音或静音文本时远程或通过触摸屏操作。这是我当前的代码,如果调用 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>

标签: javascripthtmlcsstelnet

解决方案


比方说,您想text1对应 的行为mute-on,即打开red时打开,并text表现得像mute-off,即打开时变为green(如有必要,切换)。我还将假设您希望根据您的内联 CSS切换关闭颜色text1to bewhite和 for textto be 。crimson

那么这里有一个简单的方法来做到这一点:

a) 在下面的 HTML 代码周围添加一个容器元素,并为其指定 class 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-on和添加mute-off到具有 idtext1和的元素中text

<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) 最后,为了使内联定义的默认颜色 ( whiteand crimson) 不会覆盖切换颜色 ( redand green),或者

  • 添加!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; 
    }
    

希望这可以帮助!


推荐阅读