为什么一个html元素的onmouseup事件在拖放期间没有触发?

时间:2012-02-08 02:46:29

标签: javascript html drag-and-drop onmouseup

在我看来,关于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>

1 个答案:

答案 0 :(得分:1)

当我在 target内上下鼠标时,它似乎对我有用,这里是你的代码的“jsfiddle”,加上目标周围的黑色边框:{{ 3}}

然而,当我向下鼠标并将鼠标“拖动”到目标区域之外,然后鼠标向上 - 没有事件被触发。我想说这与鼠标不再在目标区域中的事实有关。

这个小提琴:http://jsfiddle.net/prsYk/表示当您将事件附加到document对象时,这两个事件仍然会触发,您当前正将它们附加到t目标,该目标是黑色边框。

如果实施实际拖动,当移动鼠标时元素会改变其位置,那么onmouseup事件应该在您释放时触发,因为您仍在目标区域内。

不是重新发明轮子,也许Javascript库可能有助于消除实现实际拖放功能的痛苦:

上述两个库也将为您提供操作DOM元素的便捷方法,以及更多 - 我注意到你要了解'获取元素'的'todo'注释。

希望有所帮助!