开发者

Detecting drag drop to HTML textbox?

开发者 https://www.devze.com 2023-01-13 07:49 出处:网络
I have a normal search box on my webpage. It is filled with text: Search this we开发者_如何学Cbsite

I have a normal search box on my webpage. It is filled with text: Search this we开发者_如何学Cbsite

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

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

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.


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;
        }
    }
})();

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.

Drag Operations - MDC


Have you tried to use the onchange event?

BTW, there is a nifty little jQuery plugin called jquery-defaultvalue which handles all the corner cases for you. If you're using jQuery anyway, it's worth a look.


See - http://www.simplecoding.org/drag-drop-s-ispolzovaniem-html5.html , but page on the russian language (Google Translate would help).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号