是否检测到HTML文本框的拖放? [英] Detecting drag drop to HTML textbox?

查看:59
本文介绍了是否检测到HTML文本框的拖放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一个普通的搜索框.它用文本填充:Search this website

I have a normal search box on my webpage. It is filled with text: Search this website

当您在框中单击以键入搜索查询时,该文本将被删除:

This text is removed when you click into the box to type your search query:

onfocus="if(this.value=='Search this website') { this.value=''};

但是,如何像我自己经常做的那样,检测到何时有人将文本从页面拖到搜索框上? onfocus不会被触发,并且之前的文本会保留.

But how can I detect when someone drags text from the page onto the search box, as I often do myself? onfocus is not triggered and the previous text remains.

推荐答案

您需要使用 ondrop 事件,该事件仅在 ondragenter ondragover 事件已取消.事实证明,这有点棘手,因为Firefox中的行为不同于IE,Safari和Chrome.

You need to use the ondrop event, which will only fire if the ondragenter and ondragover events are cancelled. Turns out it's a bit trickier than that because the behavior is different in Firefox than IE, Safari and Chrome.

(function () {
    var inp = document.getElementById("test"),
        chg = false;

    inp.ondragover = inp.ondragenter = function () {
        chg = inp.value == "Drop here";
        return false;
    }
    inp.ondrop = function (evt) {
        evt = evt || event;

        if (chg) {
            this.value = evt.dataTransfer.getData("text")
                         || evt.dataTransfer.getData("text/plain");
            return false;
        }
    }
})();

示例-Firefox 3 +,IE5 +,Chrome和Safari.据我所知,Opera不支持该事件.至少您可以使它对95%的访问者有效.

Example - Firefox 3+, IE5+, Chrome and Safari. Near as I can tell, Opera doesn't support the event. At least you can get it working for 95% of your visitors though.

拖动操作-MDC

这篇关于是否检测到HTML文本框的拖放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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