如果用户将光标拖离 div,如何使 "onmouseup" 起作用

How to cause "onmouseup" to function if the user drags the cursor off the div

请注意,如果您 onmousedown越过 div,它会从绿色变为红色。这是意料之中的。但是,如果您按住鼠标并将光标拖离 div,然后松开鼠标,onmouseup 将不起作用,因为光标不再悬停在 [=30] 上=]. 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(),它允许您在鼠标离开元素时更改内容。

这里是 link 了解更多信息

或者你应该使用 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>