每当用户在 HTML 文档上按下鼠标并在释放按钮之前拖动鼠标时,他移动的内容就会被选中。
我正在创建一个 jquery slider ,我想取消此事件,这样当用户将鼠标向下拖动到文本上方时,文本不会被选中。
此示例有效:http://www.filamentgroup.com/examples/slider/index2.php
如果您在光标位于“This is an example from the...”文本上时启动 mousedown,则该文本被选中。
但是,如果您在光标位于滚动条上方时启动 mousedown,然后将鼠标移动到“这是来自...的示例”文本,则在您将光标移动到文本上。
他们如何取消文本的选择?
谢谢。
最佳答案
我建议创建一个 CSS 类,并在 mousedown
事件触发时将其添加到 body 元素,并在 mouseup
事件(或窗口 >blur
事件)触发:
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);
});
关于javascript - jquery取消选择事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5437597/