【问题标题】:Preventing the selection of text working in IE but not in Chrome?防止选择在 IE 中工作但在 Chrome 中不工作的文本?
【发布时间】:2016-04-07 04:55:04
【问题描述】:

我看过一些关于阻止选择文本的不同帖子,但由于某种原因,这段代码阻止了在 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-model)突出显示。

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

谁能告诉我为什么会这样以及如何解决它?

谢谢!

【问题讨论】:

    标签: javascript css angularjs google-chrome browser


    【解决方案1】:

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

    这是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 中,它允许我实际突出显示文本,但是当你第一次点击鼠标时将其删除,而在 IE 中,它允许我每次都做同样的事情时间。我认为这让用户感到困惑。有没有办法让它完全不突出显示,并且输入元素中的闪烁光标永远不会移动。我在 IE 中使用 css 'user-select' 获得了这种效果,但由于某种原因,它在 chrome 中不起作用。如果我能得到完全相同的效果,则 JS 选项很好。谢谢
    • @techer 到目前为止我还没有找到任何 css 解决方案,或者为什么在 chrome 中会发生这种情况。让我们等待其他答案:)
    【解决方案2】:

    这是为我解决它的有效解决方案: Disable Text Selection in 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 即可工作。

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 2016-07-07
      • 1970-01-01
      • 2015-02-12
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2017-07-21
      相关资源
      最近更新 更多