阻止在输入文本字段上进行选择
Prevent select on input text field
我试图通过以下注意事项阻止对输入字段进行选择
- 阻止使用鼠标进行选择
- 阻止使用键盘进行选择(包括 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
元素上定义了width
和height
,也可以使用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>
相关文章:
- 禁用/启用基于单选/选择选项所选Javascript的文本框
- ui.grid 行无法选择行
- 根据换行符选择文本
- 基于单选/选择选项重定向
- 单击提交时存储输入单选选择
- 如何使用regex在多行中选择包含任意字符的值
- 如何在多选选择框后调用javascript方法
- 在文档加载和函数调用时,行的选择方式不同
- jQuery Mobile:单选选择菜单值干扰多选菜单的处理程序
- 多个文本字段,根据单选选择显示/隐藏(Html,JS)
- HTML 行表选择
- 在单选选择中更改前缀货币符号
- 单击单选选择时动态显示 DIV
- 检查是否进行了单选选择
- 基于下拉选择的单选选择/取消选择
- 防止单选选择与时间选择重叠
- 所选选择框中更新选项的性能
- 使jqGrid多选选择在分页、工具栏搜索或筛选后保持不变
- 如何触发对复选框的更改或单击行以选择表行
- 在表格行中选择单选按钮时,行的颜色应该更改