2014-02-18 24 views
8

我有代碼選擇文本,當用戶點擊p標籤,但我不想這樣做,當用戶選擇裏面的文本。是否可以檢測點擊,但沒有拖動?如何檢測點擊,但不使用jQuery拖動?

我有簡單的代碼是這樣的:

$('.conteiner').on('click', 'p.xxx', function() { 
    $(this).selection(); 
}); 

但點擊即使我鼠標按下和MouseUp之間拖動被執行。該選擇是一個使用getSelection或Rage選擇文本的插件。

+0

你能提供一個小提琴演示? – 2014-02-18 10:41:34

回答

11

與此類似:Can you detect "dragging" in jQuery?

你可以使用鼠標按下和mouseup檢測是否有一個拖累。

$(function() { 
    var isDragging = false; 
    $(".conteiner") 
    .mousedown(function() { 
     $(window).mousemove(function() { 
      isDragging = true; 
      $(window).unbind("mousemove"); 
     }); 
    }) 
    .mouseup(function() { 
     var wasDragging = isDragging; 
     isDragging = false; 
     $(window).unbind("mousemove"); 
     if (!wasDragging) { 
      $(this).selection(); 
     } 
    }); 
    }); 

這裏是plunker演示: http://embed.plnkr.co/Y7mrOP/

+2

什麼是'var counter = 0;'在做什麼? –

0

找到更好的辦法,因爲我需要檢測拖動來選擇文本這個工作得更好:

var get_selected_text = (function() { 
    if (window.getSelection || document.getSelection) { 
     return function() { 
      var selection = (window.getSelection || document.getSelection)(); 
      if (selection.text) { 
       return selection.text; 
      } else { 
       return selection.toString(); 
      } 
     }; 
    } else if (document.selection && document.selection.type !== "Control") { 
     return function() { 
      return document.selection.createRange().text; 
     }; 
    } 
    return function() { 
     return ''; 
    }; 
})(); 

self.mouseup(function() { 
    if (get_selected_text() === '') { 
     // click not drag 
    } 
}); 
相關問題