javascript - 如果用户将光标拖离 div,如何使“onmouseup”起作用
问题描述
请注意,如果您onmousedown
越过 div,它会从绿色变为红色。这是意料之中的。但是,如果您按住鼠标并将光标拖离 div,然后放开鼠标,onmouseup
则不会起作用,因为光标不再悬停在 div 上。div 保持红色,而不是返回其初始绿色状态。
我应该使用onmousemove
吗?
任何想法如何解决这个问题?
function mouseDown() {
document.getElementById("test").style.backgroundColor = "red";
}
function mouseUp() {
document.getElementById("test").style.backgroundColor = "green";
}
#test {
position: absolute;
height: 50px;
width: 100px;
background-color: green;
}
<div id="test" onmousedown="mouseDown()" onmouseup="mouseUp()">
</div>
解决方案
function mouseDown() {
document.getElementById("test").style.backgroundColor = "red";
document.getElementsByTagName("BODY").onmouseup = function() {mouseUp()};
}
function mouseUp() {
document.getElementById("test").style.backgroundColor = "green";
}
#test {
position: absolute;
height: 50px;
width: 100px;
background-color: green;
}
<body>
<div id="test" onmousedown="mouseDown()" onmouseup="mouseUp()"
onmouseout="mouseUp()">
</div>
</body>
您应该使用onmouseout()
which 允许您在鼠标离开元素时更改内容。
这是更多信息的链接
或者你应该mouseup
在我们的例子中使用父元素 div 元素,id=full
看这里
function mouseDown() {
document.getElementById("test").style.backgroundColor = "red";
}
function mouseUp() {
document.getElementById("test").style.backgroundColor = "green";
}
#test {
position: absolute;
height: 50px;
width: 100px;
background-color: green;
}
#full{
width: 100%;
height: 2000px;
background: blue;
}
<body>
<div id="full" onmouseup="mouseUp()" >
<div id="test" onmousedown="mouseDown()" onmouseup="mouseUp()">
</div>
</div>
</body>