Javascript 禁用单击 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11186666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:50:20  来源:igfitidea点击:

Disable click on a div

javascript

提问by Mageek

I want to disable click on a certain <div>so that when you select the text on it, the text doesn't select.

我想禁用某个特定的点击,<div>以便当您选择其上的文本时,该文本不会被选择。

I tried writing onclick="return false;"like in this fiddle http://jsfiddle.net/mageek/X6hqD/but it doesn't work.

我试着onclick="return false;"像在这个小提琴http://jsfiddle.net/mageek/X6hqD/ 中那样写,但它不起作用。

How can it work? (My goal isn't just disabling the select, it's the whole click).

它如何工作?(我的目标不仅仅是禁用选择,而是整个点击)。

回答by Kasidesh Yontaradidthaworn

document.getElementById('div1').onmousedown = new function ("return false");

回答by Christoph

If you want to disable selection of the text only, use:

如果您只想禁用文本选择,请使用:

<div onselectstart='return false;'>
    text
</div>

div{
   -moz-user-select: none;-webkit-user-select: none;
   -khtml-user-select:none;o-user-select:none;
   user-select: none;
}

回答by PraveenVenu

You can try this CSS

你可以试试这个 CSS

<style type="text/css" media="print,screen" >
  .unselectable {
     -webkit-touch-callout: none;
     -webkit-user-select: none;
     -khtml-user-select: none;
     -moz-user-select: none;
     -ms-user-select: none;
     user-select: none;
   }
    </style>

<div class="unselectable">
asdasdsadsadsad<br>asdasdasd
</div>

<br><br>

<div>
qqqqqqqqqqqqqqqq<br>asdasdasd
</div>

回答by jittakal

<div id="div-test-id" style="width:100px;height:100px;background-color:yellow;">Lorem ipsum</div>

<script type="text/javascript">
var div_click_escape=function(eventObject){
      return false;
};

$(function(){
    $("#div-test-id").click(div_click_escape);
    $("#div-test-id").mousedown(div_click_escape);
    $("#div-test-id").mouseup(div_click_escape);
}
</script>

Will avoid to select the text.

将避免选择文本。