为什么一个html元素's的onmouseup事件在拖放过程中未触发

why one html element's onmouseup event is not firing during drag and drop?

本文关键字:事件 onmouseup 拖放 过程中 一个 html 元素 为什么      更新时间:2023-09-26

在我看来,所有关于html拖放的教程都将onmousedown和onmouseup事件设置为文档,而不是元素本身,正如我用以下代码测试的那样,当点击元素时,onmousedown和onmouseup事件都会被触发,但是,当尝试拖动元素并将其放置在另一个位置时,onmouseup事件不会触发,

我使用以下代码,我的问题是:为什么onmouseup在拖动时没有被激发?我使用firefox 8.0.1

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Border</title>
<style type="text/css">
body{
background-color: gray;
}
#page{
margin: 20px auto;
width:800px;
height:639px;
/*background-image: url("./img/board.jpg");*/
background-image: url("https://www.google.com/logos/2012/dickens-2012-HP.jpg");
background-repeat:  no-repeat;
}
#target{
position: relative;
top: 10px;
left: 20px;
/*background-image: url("./img/target.jpg");*/
background-image: url("https://www.google.com/images/icons/product/chrome-48.png");
background-repeat:  no-repeat;
width: 145px;
height:117px;
}
</style>
<script type="text/javascript">
function mylog(msg)
{
    if(window.console && console.log){
        console.log(msg);
    }
}

window.onload = function(){ 
    initdragdrop();
}
/* 
todo: learn how to make a getObject()
function getObject(id){
    var t = document.getElementById(id);
    this.x = t.left;
    this.y = t.top;
}
 */
function initdragdrop(){    
    var t = document.getElementById('target');

    t.onmousedown = function(){
        this.status = 'down';
        mylog(this.status);
    }

    t.onmouseup = function(){
        this.status = 'up';
        mylog(this.status);
    }
}
</script>
</head>
<body>
<div id="page">

<div id="target">
</div>
</div>

</body>
</html>

当我在target中上下移动时,它似乎对我有效,这里有一个代码的"jsfiddle",加上目标周围的黑色边框:http://jsfiddle.net/prsYk/

但是,当我向下鼠标并将鼠标"拖动"到目标区域之外,然后向上鼠标时,不会触发任何事件。我想说,这与鼠标向上移动时,鼠标不再位于目标区域这一事实有关。

这把小提琴:http://jsfiddle.net/V4HPw/显示当您将事件附加到document对象时,这两个事件仍然会激发,而您当前正在将它们附加到具有黑色边框的元素t目标。

如果您实现了实际拖动,其中元素在移动鼠标时会更改其位置,那么释放时onmouseup事件应该会激发,因为您仍在目标的区域内。

与其重新发明轮子,也许Javascript库可以帮助消除实现实际拖放功能的痛苦:

  • YUI DragDrop模块
  • jquery可拖动

以上两个库还将为您提供操作DOM元素的方便方法,以及更多内容——正如我注意到的关于"获取元素"的"todo"注释所示。

希望能有所帮助!