How to trigger draggable behaviour programmatically

左心房为你撑大大i 提交于 2019-12-04 05:40:04

I managed to get this working. As I suspected, it had something to do with event handling.

The fix was simple: I modified the above code to check if the event target was the same as the element to which the callback was bound (ie, slider bounding box). On the initial click that repositions the handle, these are the same elements. However, when the handle's mousedown event is triggered, and the event bubbles up to the bounding box, the target of that event is the slider handle. So, they don't match, and the trigger event isn't called again, setting off an infinite loop.

At least I think that's what's going on. In any case, here's the code that worked:

$(".Slider2d").mousedown(function(event){
    // get location of click and reposition handle to click location 

    handle = $(".Slider2d").children(".Slider2dHandle");
    if ($(this).attr("id") == $(event.target).attr("id")) {
        handle.trigger(event);
    }
});

Or you could just stop propagation at the handler's mousedown event so it doesn't bubble up to the slider's mousedown event.

$(".Slider2d").mousedown(function(event) {
    // get location of click and reposition handle to click location 

    handle = $(".Slider2d").children(".Slider2dHandle");
    handle.trigger(event);
});

$(".Slider2dHandle").mousedown(function(event) {
    event.stopPropagation();
});

This doesn't work for me, so I assume I'm doing something wrong. But I was wondering, if it works for you, why not set:

if ($(this).attr("id") == $(event.target).attr("id"))

To this:

if (this === event.target)

I'll update once I figure this out.

Still nothing: during that infinite loop, the event.target remains as the slider, not the handle, only then is the second event actually triggered.

EDIT: Got it, I switched from jQuery 1.7.1 to 1.6.4 and it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!