How to bind JQuery draggable to a hover event

2019-09-05 17:41发布

问题:

I'm having a tough time in finding a solution for following effect.

Imagine having a container "#container" containing:

  • An element "#element" that should only be draggable horizontally and within it's parent ("#container")
  • A handle "#handler" which should be the dragging handle.

Now the whole thing shold be dragged on hover.

Up to now I have following code, but don't know what to do:

<script>
    $("#element").dragable({handle: "#handler",  axis: "x", containment: "#container"});
</script>

How can I do this?

回答1:

You don't mention when you want it to -stop- dragging. My solution is to do so when the mouse leaves the container, though you don't have to. You could have the dragging element follow the mouse everywhere on the screen like those creepy X-eyes on screen...

http://jsfiddle.net/pabo/5xAkQ/

// set the element to be draggable
$('div#drag').draggable({
    containment: "parent"
});

// mousing over the handle starts dragging
$('div#handle').hover(function (e) {
    e.type = 'mousedown';
    $('div#drag').trigger(e);
});

// mouse leaving the container stops dragging
$('div#container').mouseleave(function (e) {
   e.type = 'mouseup';
    $('div#drag').trigger(e);
});