浏览器事件不冒泡
我想让拖放到元素上,并且我不希望该元素的父元素捕获单击或拖动事件,因此我使用气泡模型,但是我要拖动的元素包含拥有相同元素的子元素该元素的大小(宽度、高度、左侧...)。
例如:
<div id="div_con" style="left: 20px; top: 50px; width: 181px; height: 357px; position: absolute; z-index: 10; cursor: pointer;" class="drag">
<img src="test.PNG" id="Over_Label_1912694_Img" style="left: 0px; top: 0px; width: 181px; height: 357px; position: relative;">
</div>
div#div_con
是我想要拖动的元素,但由于 div#div_con
和 img 具有相同的大小,因此用户永远无法单击 >div#div_con
。因为img在它上面。
所以我将 mouseDown
、mouseMove
、mouseUp
事件绑定到整个文档:
document.onmousedown = OnMouseDown;
document.onmouseup = OnMouseUp;
在我看来,当用户单击 下的 img 时div#div_con
,mouseDown
事件将冒泡到 div#div_con
。
因为我只想拖动 div#div_con
,所以我在 mouseDown
处理程序中进行检查:
if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag')
{ //do the start the move}
但它不起作用。
这是完整的示例:
I want to make the drag drop to the element,and I dot not want the parent of this element capture the click or drag event, so I use the bubble model, however the element which I want to drag contain a child who own the same size (width, height, left...) of this element.
For example:
<div id="div_con" style="left: 20px; top: 50px; width: 181px; height: 357px; position: absolute; z-index: 10; cursor: pointer;" class="drag">
<img src="test.PNG" id="Over_Label_1912694_Img" style="left: 0px; top: 0px; width: 181px; height: 357px; position: relative;">
</div>
div#div_con
is the element I want to drag, but since the div#div_con
and the img have the same size, so user can never click the div#div_con
. Since the img is above it.
So I bind the mouseDown
, mouseMove
, mouseUp
events to the whole document:
document.onmousedown = OnMouseDown;
document.onmouseup = OnMouseUp;
In my opinion,when user click the img under the div#div_con
, the mouseDown
event will bubble to div#div_con
.
Since I just want to drag the div#div_con
,so I make a check in the mouseDown
handler:
if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag')
{ //do the start the move}
But it does not work.
This is the complete example:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
但它正在冒泡。这就是文档首先接收事件的原因。您遇到的问题是 event.target 指的是单击的对象,而 event.currentTarget 指的是正在侦听的对象,而这些都不是您的 div。
您要么需要直接在 div 上使用事件侦听器,要么需要获取
target.parentElement
然后将其用作 _dragElement。查看一下。
But it is bubbling. That's why document is receiving the event to begin with. The problem you're experiencing is that event.target refers to the object clicked, and event.currentTarget refers to the object listening and neither one of those are your div.
You will either need to use an event listener on the div directly, or you'll need to get
target.parentElement
and then use that as _dragElement.Check it out.
如果您将图像指定为
DIV
的background-image
并删除IMG
,则拖动并删除IMG
即可。掉落作品: http://jsfiddle.net/HxaJ4/If you specify the image as
background-image
of theDIV
and remove theIMG
drag & drop works: http://jsfiddle.net/HxaJ4/