javascript - 如何使用 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>
解决方案
比方说,您想text1
对应 的行为mute-on
,即打开red
时打开,并text
表现得像mute-off
,即打开时变为green
(如有必要,切换)。我还将假设您希望根据您的内联 CSS切换关闭颜色text1
to bewhite
和 for text
to 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) 最后,为了使内联定义的默认颜色 ( white
and crimson
) 不会覆盖切换颜色 ( red
and 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; }
希望这可以帮助!
推荐阅读
- vba - 如何在 vba 中重置定期会议?
- arrays - 按建议的键对 Swift 数组进行排序
- javascript - 如何将两个数组数据合并成一个数组?
- android - Android NN中关于conv2D的问题:输出形状限制
- vhdl - 我如何用状态自动表示所有卷曲?
- data-structures - 是否可以使用 4 个队列实现 n 个堆栈?
- amazon-web-services - 如果我使用 AWS CLI S3 'mv' 命令,那背后是什么类型的请求?
- npm - 如何在 npm 中安装最新的 SNAPSHOT 版本?
- java - 替代主键列 varchar(max)
- azure - 为什么我们只能将基本的动态 PIP 分配给 Azure 上的虚拟网络网关?