javascript - 如何使用 JavaScript 更改每个列表项的背景颜色?
问题描述
当我将鼠标移到列表上时,我正在努力尝试更改列表中每个项目的背景颜色。
我有一个或多或少这样的列表:
<ul id="ul_menu">
<li>
<a href="#ref" title="go to ref" id="menu_selector" onmouseover="mouseOver()" onmouseout="mouseOut()">Text</a>
</li>
<li>
<a href="#ref" title="go to ref" id="menu_selector" onmouseover="mouseOver()" onmouseout="mouseOut()">Text</a>
</li>
<li>
<a href="#ref" title="go to ref" id="menu_selector" onmouseover="mouseOver()" onmouseout="mouseOut()">Text</a>
</li>
</ul>
我正在尝试使用 Javascript 进行如下操作:
var list = document.getElementByID("ul_menu");
var listItems = ul.getElementsByTagName("li");
function mouseOver() {
for (li in listItems){
li.style.backgroundColor = "yellow";
}
}
function mouseOut() {
for (li in listItems){
li.style.backgroundColor = null;
}
}
我正在使用 XSLT 从 XML 文件动态生成此 HTML 代码,因此我无法为每个列表项选择特定的 ID。
你可以帮帮我吗?
谢谢大家。
解决方案
如果我没看错(如果没看错请告诉我),当鼠标指针悬停在列表项上时,您只想更改文本的背景颜色,对吗?
如果是这样,你可以用一点 CSS 很容易地做到这一点:
.yellow:hover {
background-color: yellow;
}
<ul>
<li>
<a href="#ref" title="go to ref" class="yellow">Text</a>
</li>
<li>
<a href="#ref" title="go to ref" class="yellow">Text</a>
</li>
<li>
<a href="#ref" title="go to ref" class="yellow">Text</a>
</li>
</ul>
如果您真的想使用 JavaScript,它仍然是可能的,但您需要指定突出显示区域的宽度。尝试这样的事情:
function yellowa1(x) {
a1.style.backgroundColor = "yellow";
a1.style.width = "5px";
}
function yellowb2(x) {
b2.style.backgroundColor = "yellow"
b2.style.width = "5px";
}
function yellowc3(x) {
c3.style.backgroundColor = "yellow"
c3.style.width = "5px";
}
function nulla1(x) {
a1.style.backgroundColor = "transparent";
}
function nullb2(x) {
b2.style.backgroundColor = "transparent";
}
function nullc3(x) {
c3.style.backgroundColor = "transparent";
}
<body>
<ul>
<li onmouseover="yellowa1(this)" onmouseout="nulla1(this)" id="a1">a</li>
<li onmouseover="yellowb2(this)" onmouseout="nullb2(this)" id="b2">b</li>
<li onmouseover="yellowc3(this)" onmouseout="nullc3(this)" id="c3">c</li>
</ul>
</body>
此外,为了将来参考,请注意 anid
用于标识一个元素,而 aclass
可用于标识多个元素。同样,只有DOM 方法I
的部分应该大写,而不是两个字母。并确保您的元素已定义。Id
.getElementById
<ul>
推荐阅读
- r - R中特定行与前一行之间的滞后差异
- python-requests - jupyterlab:在笔记本中打开 HTML(使用远程连接)
- netsuite - 使用 Emp Center 角色的 Vendor Bill Approval 拒绝原因
- php - 数组和json解码问题
- c# - 在 BlazorFluentUI WebAssembly 中执行 JS 互操作时发生异常错误
- c++ - 从调用 lambda 函数调用 xmlParserInit() 来初始化静态变量是一个坏主意吗?
- asp.net - VS Code sftp 到 docker 内的 appsettings 文件
- html - 如何使用 css 在图像上添加浅色滤镜?
- kubernetes - 停止 TLS 证书由 cert-manager 自动重新创建
- scala - 驱动程序吊舱保持运行