<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta />
<title>Test</title>
<style type="text/css">
ul{
list-style:none;
}
li{
background-image:url(Winter.jpg);
width:100px;
}
</style>
<script type="text/javascript">
var lis=document.getElementsByTagName("li");
for(var i=0;i<lis.length;i++){
lis[i].onmouseover=function(){
this.style.backgroundImage="url(Sunset.jpg)";
}
lis[i].onmouseout=function(){
this.style.backgroundImage="url(Winter.jpg)";
}
}
</script>
</head>
<body>
<ul>
<li>aaa</li>
<li>bbb</li>
<li>ccc</li>
</ul>
</body>
</html>
var lis=document.getElementsByTagName("li");
这一行调试了,为什么lis数组长度一直为0,如何解决
js代码放置的位置不对,要么像下面这样放到ul标签之后,要么将代码写到window.onload = function() {}函数中。
JS是解释型语言,边加载边解释,只有目标对象被加载到DOM树以后才能获取和操作
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>Test</title>
<style type="text/css">
ul{
list-style:none;
}
li{
background-image:url(Winter.jpg);
width:100px;
}
</style>
</head>
<body>
<ul>
<li>aaa</li>
<li>bbb</li>
<li>ccc</li>
</ul>
<script type="text/javascript">
var lis=document.getElementsByTagName("li");
for(var i=0;i<lis.length;i++){
lis[i].onmouseover=function(){
this.style.backgroundImage="url(Sunset.jpg)";
}
lis[i].onmouseout=function(){
this.style.backgroundImage="url(Winter.jpg)";
}
}
</script>