Javascript/Jquery语法禁用Div上的文本选择和所有子元素

Javascript/Jquery Syntax to Disable Text Selection on a Div AND all Child Elements?

本文关键字:选择 文本 元素 Jquery 语法 Div Javascript      更新时间:2023-09-26

在div及其所有子元素上禁用文本选择的语法是什么。我使用$("#MyContent).disableSelection()禁用下面代码中的所有文本,它在firefox中工作,并同时禁用所有三行。

在IE explorer 9中,它不适用于子元素,所以要禁用所有文本,我必须执行$("#text1).disableSelection(),$("#text2).disaleSelection(),$["#text3".disableSelection()。一次禁用或将其应用于所有子元素的语法是什么?

<div id="MyContent">
  <div id="text1">Hello World</div>
  <div id="text2">Goodbye</div>
  <div id="text3">Asdf</div>
</div>

这对我有效:

$('#MyContent').children().each(function(i, c) {
    disableSelection(c);
});
function disableSelection(target) {
    console.debug(target);
    if (typeof target.onselectstart != "undefined")             // For IE
        target.onselectstart = function() { return false };
    else if (typeof target.style.MozUserSelect != "undefined")  // For Firefox
        target.style.MozUserSelect = "none";
    else                                                        // All other routes (Opera, etc.).
        target.onmousedown = function() { return false };
    target.style.cursor = "default";
}

演示:http://jsfiddle.net/9vLFD/4/

您可以尝试

$('#MyContent').children().each(function(i,c){
    $(c).disableSelection();
});