首页 > 解决方案 > 如何使用 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。

你可以帮帮我吗?

谢谢大家。

标签: javascripthtmlcssxmlxhtml

解决方案


如果我没看错(如果没看错请告诉我),当鼠标指针悬停在列表项上时,您只想更改文本的背景颜色,对吗?

如果是这样,你可以用一点 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>


推荐阅读