阻止选择在IE中工作但不在Chrome中工作的文本

Preventing the selection of text working in IE but not in Chrome?

本文关键字:工作 Chrome 文本 IE 选择      更新时间:2024-01-12

我看到过几篇关于阻止选择文本的不同帖子,但出于某种原因,这段代码阻止了IE中的选择,而不是Chrome中的选择。。我不明白为什么…

 <input type="text" class="form-control no-select" name="inputField" placeholder="Select" ng-model="ctrl.ngModelValue">
 .no-select {
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* IE/Edge */
  user-select: none;  
}  

我基本上想防止在输入中突出显示文本(ng模型)。

上面的代码阻止我在IE中选择文本,但出于某种原因,我仍然可以在Chrome中突出显示输入元素中的文本?当涉及到工作时,通常情况是相反的。

有人能告诉我为什么会发生这种情况以及如何解决吗?

谢谢!

好吧,我不知道如何在input字段中使用css来解决这个问题,user-select: none规则将很好地应用于其他标签,如<p> <div>等。

这是为您提供的JavaScript解决方案

请参阅FIDDLE

var inp = document.getElementById('myElement');
inp.addEventListener('select', function() {
  this.selectionStart = this.selectionEnd;
}, false);
.no-select {
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* IE/Edge */
  user-select: none;  
}  
 <input type="text" id="myElement" class="form-control no-select" name="inputField" placeholder="Select" ng-model="ctrl.ngModelValue">
 
 <p class="no-select">
 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque quas, illo iste! Obcaecati quisquam, error doloremque, numquam iste, laboriosam possimus nostrum optio aperiam, distinctio quo accusamus cum molestias! Est, at!
 </p>

以下是为我解决问题的工作解决方案:禁用Chrome 中的文本选择

   window.onload = function() {
      var element = document.getElementById('content');
      element.onselectstart = function () { return false; } // ie
      element.onmousedown = function () { return false; } // mozilla
 }

上面指定了一个特定的元素,并禁用了文本的选择。适用于Chrome、IE和Firefox。这在没有任何css的情况下工作。