防止在输入文本字段上选择 [英] Prevent select on input text field

查看:62
本文介绍了防止在输入文本字段上选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于以下考虑,我试图防止在输入字段上进行选择

I am trying to prevent selection on an input field with the following considerations

  • 防止使用鼠标进行选择
  • 防止使用键盘选择(包括Ctrl + A,Shift +箭头)
  • 允许使用键盘和鼠标聚焦到领域

到目前为止,我已经尝试了以下方法:

So far I have tried these things:

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;
}

结果:仍然可以选择

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

I have also tried below with no success:

$("#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();
});

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

Result: console printed the message, however the select still works

感谢您的帮助

推荐答案

可以通过在

It can be done by setting the element's selectionStart to selectionEnd on select event:

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

这篇关于防止在输入文本字段上选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆