开发者

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜