简体   繁体   中英

jQuery Drag only works in Chrome

I don't want to use the jQuery UI, so I tried to make a jQuery Drag Script on my own.

This is basically my code for horizontal Dragging:

var down = false;

$('#itemToMove').mousedown(function(e){
    down = true;
    left = event.pageX - $(this).offset().left;
});

$(document).mouseup(function(){
    down = false;
});

$(document).mousemove(function(e){
    if(down){
        var X = event.pageX - left;
        $('#itemToMove').css({
            left: X
        });
    }
});

I works just awesome in Chrome, but doesn't in other browsers (tried KHTML, Trident and Gecko). Can someone tell me why?

I am pretty damn sure that if you put an alert("") inside your mousedown event handler, it will never fire. That's because by the time you try to bind the event handler to the object's mousedown event, the object (your div) does not exist yet. Try wrapping your entire code block in

$(document).ready(function() { // Your code here });

Something like this:

    var down = false;
    var left = 0;

    $(document).ready(function()
        {
        $('#itemToMove').mousedown(function(e)
            {
            down = true;
            left = e.pageX - $(this).offset().left;
            });

        $(document).mouseup(function()
            {
            down = false;
            });

        $(document).mousemove(function(e)
            {
            if(down)
                {
                var X = e.pageX - left;
                $('#itemToMove').css(
                    {
                    left: X
                    });
                }
            });
        });

Hope it helps :]

Added: Also, make sure you skim through this document: http://api.jquery.com/ready , especially the following part:

Note: Please make sure that all stylesheets are included before your scripts (especially those that call the ready function). Doing so will make sure that all element properties are correctly defined before jQuery code begins executing. Failure to do this will cause sporadic problems, especially on WebKit-based browsers such as Safari.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM