jquery cancelling select event
Whenever the user does a mousedown on an HTML document and drags the mouse before he releases the button, the content he's moving over becomes selected.
I'm creating a jquery slider and I'd like to cancel this event so that when the user drags his mouse with the mouse down over when the mouse is over text, the text isn't selected.
This example works: http开发者_运维百科://www.filamentgroup.com/examples/slider/index2.php
If you start the mousedown when the cursor is over the "This is an example from the..." text, the text is selected.
However, if you start the mousedown when the cursor is over the scroll elevator and then move the mouse over the "This is an example from the..." text, the text is NOT selected while you're moving the cursor over the text.
How did they cancel the selection of the text?
Thanks.
I'd suggest creating a CSS class and adding it to the body element when the mousedown
event fires and removing it when the mouseup
event (or the window blur
event) fires:
CSS:
*.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
-ms-user-select: none; /* From IE 10 */
user-select: none;
}
JavaScript:
function switchUnselectable(node, unselectable) {
if (node.nodeType == 1) {
node.setAttribute("unselectable", unselectable ? "on" : "off");
}
var child = node.firstChild;
while (child) {
switchUnselectable(child, unselectable);
child = child.nextSibling;
}
}
function switchSelection(unselectable) {
if (unselectable) {
$("body").addClass("unselectable");
} else {
$("body").removeClass("unselectable");
}
switchUnselectable($("body")[0], unselectable);
}
var $sliderEl = $("#yourSliderId");
$sliderEl.mousedown(function() {
switchSelection(true);
});
$sliderEl.mouseup(function() {
switchSelection(false);
});
$(window).blur(function() {
switchSelection(false);
});
<div onselectstart="return false;" ondragstart="return false;">
Go ahead, just try to select me!
</div>
Here's an example!
if you are trying to create a slider, you can directly use the jQuery UI slider unless you application needs some different functionality. Hope this helps. :\
The most straightforward solution is to prevent default on the mousedown
event, which I suspect is what the linked page uses. You can often do this in the same event handler that starts tracking mouse movement on your slider. For instance, assuming jQuery:
$slider.mousedown(function(e){
e.preventDefault();
// Start tracking mouse movement
});
Some newer browsers have CSS properties which do the same job (described in other answers), but this is the simplest and most widely-used trick.
Bonus!
You can accomplish the same thing by returning false
from your event handler. This asks jQuery to prevent default on the event for you, and stop propagation of the event to event handlers on parent nodes.
精彩评论