防止选择输入文本字段

新手上路,请多包涵

我试图通过以下考虑来防止在输入字段上进行选择

  • 防止使用鼠标选择
  • 防止使用键盘进行选择(包括 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; });

Javascript

我试过下面

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

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

谢谢你的帮助

原文由 user2636664 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 152
2 个回答

可以通过将元素的 selectionStart 设置为 selectionEnd on select 事件来完成:

 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!" />

原文由 Hashem Qolami 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以阻止 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>

原文由 Unmitigated 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题