事件传播,覆盖和拖放事件 [英] Event propagation, overlay and drag-and-drop events

查看:115
本文介绍了事件传播,覆盖和拖放事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户将文件拖到窗口上时,我想在视口上覆盖一个div。

I want to overlay a div over the viewport when the user drags a file onto the window.

但是,我遇到了事件传播的问题。当我将叠加层设置为 display:block 时,它会显示一个 dragleave 事件,然后另一个 dragenter ,然后再次 dragleave ,所以它总是处于拖后状态。当然,我在事件对象上调用 e.stopPropagation() e.preventDefault()

However, I'm having trouble with the event propagation. When I set the overlay to display: block it appears to fire off a dragleave event and then another dragenter and then another dragleave again, so it's always in a post-dragleave state. Of course I call e.stopPropagation() and e.preventDefault() on the event object, but it doesn't seem to make a difference.

在窗口上拖动某个东西时,console.log()输出:

The console.log() output when you drag something over the window:

dragenter
dragenter
dragleave
dragenter
dragleave

css。默认情况下, #overlay 设置为 display:none ,但会显示 body dragenter 类:

The css. #overlay is set to display: none by default, but will show if body has the dragenter class:

    body {
        position: absolute;
        height: auto;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: 0;
        padding: 0;
    }

    #overlay {
        position: absolute;        
        height: auto;
        width: auto;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url(bg.png) repeat-x top right, url(bg.png) repeat-x bottom left, url(bg.png) repeat-y top right, url(bg.p
ng) repeat-y bottom left;
        display: none;
    }

    body.dragenter #overlay {
        display: block;
    }

javascript。在dragenter上添加'dragenter'类,并在dragleave上删除它:

The javascript. Add the 'dragenter' class on dragenter and removes it on dragleave:

$(document).on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
    console.log('dragenter');
    $(document.body).addClass('dragenter');
});

$(document).on('dragleave', function (e) {
    e.stopPropagation();
    e.preventDefault();
    console.log('dragleave';
    $(document.body).removeClass('dragenter');
});

html:

<body>
<div id="overlay">...</div>
...    
</body>

$ b b

推荐答案

感谢Scottux,让我走上正确的轨道。

Thanks to Scottux, that led me onto the right track.

我不得不隐藏#dragOverlay默认情况下用 display:none ,并显示在此事件

Only problem was it also covered up the rest of the page, so none of the elements or inputs were clickable. I had to hide #dragOverlay by default with "display: none" and display it on this event

// Display an overlay when dragging a file over
$('*:visible').live('dragenter', function(e) {
    e.stopPropagation();
    $('body').addClass('drag-enter');
});

这篇关于事件传播,覆盖和拖放事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆