Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

jquery - Trigger Click-and-Hold Event

QUESTION:

Using jQuery, how can I imitate a click-and-hold event?


I am currently beating my head against a wall and cannot seem to figure out how to go about this!

I have also tried searching on google and in forums, but to no avail.

In my current example, I am using jQuery UI's .draggable().

Ideally, I would like to do the following:

  • Perform a click/mousedown on the div.
  • Imitate a click-and-hold event and be able to move the element freely.
  • On next click/mousedown, end click-and-hold event.

When I try functions like:

$("#drag").draggable().mousedown(function(e){
    e.preventDefault();
    return $(this).mousedown();
});

It then causes an infinite loop, which will eventually result in the browser crashing. However, I am not sure how one would go about initiating a constant .mousedown() event.

Here is a demo of what I currently have: http://jsfiddle.net/vPruR/16/ .

Any help would be greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think there is some option to simulate the click-and-hold. Also it may create too much browser dependency.

So you could try something as below.

var click = false,
top = null,
left = null;

$(document).bind('mousemove', function (e) {
   if (click == true) {
      $('#drag').css({
         left: e.pageX - left,
         top: e.pageY - top
       });
    }
});

$('#drag').draggable().click(function(e) {
    top = e.pageY - $('#drag').position().top; 
    left = e.pageX - $('#drag').position().left;
    click = !click;
    return false;
});

$('html').click(function() {
    click = false;
});

DEMO: http://jsfiddle.net/dirtyd77/qbcQn/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...