阻止在输入文本字段上进行选择

Prevent select on input text field

本文关键字:行选 选择 字段 文本 输入      更新时间:2023-09-26

我试图通过以下注意事项阻止对输入字段进行选择

  • 阻止使用鼠标进行选择
  • 阻止使用键盘进行选择(包括 Ctrl+A、shift+箭头(
  • 允许使用键盘和鼠标聚焦到现场

到目前为止,我已经尝试了这些事情:

.CSS

我尝试使用以下类

.unselectable {
  -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

结果:仍然可以选择。

我也在下面尝试过,但没有成功:

$("#my_field").attr('unselectable','on')
     .css({'-moz-user-select':'-moz-none',
           '-moz-user-select':'none',
           '-o-user-select':'none',
           '-khtml-user-select':'none', 
           '-webkit-user-select':'none',
           '-ms-user-select':'none',
           'user-select':'none'
     }).bind('selectstart', function(){ return false; });

爪哇语

我尝试了以下方法

$( "#my_field" ).select(function(e) {
        console.log("Select called");
        e.preventDefault();
});

结果:控制台打印了消息,但选择仍然有效

感谢您的帮助

可以通过

将元素的selectionStart设置为select事件selectionEnd来完成:

var inp = document.getElementById('my_input');
inp.addEventListener('select', function() {
  this.selectionStart = this.selectionEnd;
}, false);
<input id="my_input" type="text" value="Try to select me!" />

您可以阻止mousedown事件以阻止选择input内的文本。

<input type="text" id="unselectable" value="You can not select this text!"/>
<script>
document.getElementById("unselectable").addEventListener("mousedown", function(event){
  event.preventDefault();
});
</script>

您可以使用绝对位置的任何图层覆盖<input>,例如使用 div.wrapper::after 或其他包装器标记。然后使用user-select: none作为包装标签(<div><label>等(,不要在<input>本身上使用user-select: none

但是,如果您的包装标签是<label>我建议另外为<input>添加属性readonly并将<label>转换为块(或内联块/弹性/内联弹性(。

input { outline: none; margin: 10px 0; width: 200px; }
.wrapper {
  position: relative;
  user-select: none;
}
.wrapper::after {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
label.wrapper { display: block; }
<div class="wrapper">
  <input type="text" value="Any text in the div wrapper"/>
</div>
<label class="wrapper">
  <input type="text" value="Any text in the label wrapper" readonly />
</label>

仅限 CSS 的解决方案:

这将不允许输入文本在视觉上显示为选中状态。
在某些情况下,如果开发人员不关心输入的文本能够复制粘贴,但只需要选择的视觉方面,则此技术已经足够好了。

input{ color:transparent }
input::selection{ color:transparent }
<input value='invisible selection'>

如果在input元素上定义了widthheight,也可以使用font-size:0

JS解决方案:

当输入聚焦时→取消聚焦(通过调用 blur 方法(:

<input value='unselectable selection' onfocus='this.blur()'>

这是何时需要带有光标的指针图标的解决方案。

.input-select {
  position: relative;
  user-select: none;
  cursor: pointer;
}
.input-select::after {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="input-select">
  <input type="text" value="any"/>
</div>