这是一个鼠标移入是红色鼠标移出变绿色的例子
<head>
<title>Title</title>
<style>
#div1{
width: 200px;
height: 200px;
background: red;}
</style>
<script>
function toGreen(){
document.getElementById('div1').style.width="300px";
document.getElementById('div1').style.height="300px";
document.getElementById('div1').style.background="green";
}
function toRed(){
document.getElementById('div1').style.width="200px";
document.getElementById('div1').style.height="200px";
document.getElementById('div1').style.background="red";
}
</script>
</head>
<body>
<div id="div1" onmouseover="toGreen()" onmouseout="toRed()"></div>
</body>
下面是改进:通过使用变量
<script>
function toGreen(){
var oDiv= document.getElementById('div1');
oDiv .style.width="300px";
oDiv.style.height="300px";
oDiv.style.background="green";
}
function toRed(){
var oDiv= document.getElementById('div1');
oDiv.style.width="200px";
oDiv.style.height="200px";
oDiv.style.background="red";
}
</script>