如何用JavaScript改变列表中每个项目的背景颜色?

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

当我把鼠标移到一个列表中的每个项目上时,我正在努力改变它的背景颜色。

我有一个列表,差不多是这样的。

<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。

您能帮帮我吗?

谢谢大家。

javascript html css xml xhtml
1个回答
0
投票

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

如果是这样,你可以通过一个小小的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>

另外,为了方便以后的参考,请注意,一个... id 是用来识别一个元素,而 class 可以用来识别几个。以及,只有 IId DOM方法的一部分 .getElementById 应该是大写,而不是两个字母。并确保你的 <ul> 元素被定义。


0
投票

 #ul_menu li:hover{
     background-color: yellow;
 }
//Try using just CSS to achieve the result if you don't mind
<ul id="ul_menu">
  <li>
    <a href="#ref" title="go to ref" id="menu_selector" >Text</a>
  </li>
  <li>
    <a href="#ref" title="go to ref" id="menu_selector" >Text</a>
  </li>
  <li>
    <a href="#ref" title="go to ref" id="menu_selector">Text</a>
  </li>
</ul>
© www.soinside.com 2019 - 2024. All rights reserved.