你可以这样做:
<div id="div" onmouseover="over_div()" onmouseout="out_div()" onclick="click_div()" style="width:100px; height:100px; border:2px solid black"></div>
<script type="text/javascript">
var isClicked = false;
function click_div(){
isClicked = true;
document.getElementById("div").style.backgroundColor="red";
}
function over_div(){
if(!isClicked )
document.getElementById("div").style.backgroundColor="green";
}
function out_div(){
if(!isClicked )
document.getElementById("div").style.backgroundColor="white";
isClicked = false;
}
</script>
但是,使用全局变量是一种不好的做法。如果你理解闭包的概念,你可以使用这样的东西:
<div id="div" style="width:100px; height:100px; border:2px solid black"></div>
<script type="text/javascript">
(function()
{
var div = document.getElementById("div");
var isClicked = false;
div.addEventListener("click", function() {
div.style.backgroundColor = "red";
isClicked = true;
});
div.addEventListener("mouseover", function() {
if(!isClicked)
div.style.backgroundColor = "green";
});
div .addEventListener("mouseout", function() {
if(!isClicked)
div.style.backgroundColor = "white";
isClicked = false;
});
}
)();
</script>
使用它,div
andisClicked
变量不会与稍后在您的代码中可能具有相同名称的其他变量发生冲突。