在文本区域中禁用文本选择 [英] Disable text selection in textarea
问题描述
我需要找到一种方法来防止用户选择文本区域中的文本.目的是创建一个自定义键盘,用于在文本区域中输入文本.我希望用户能够单击文本区域来设置插入标记的位置(该标记现在已经在工作).但是,我不希望用户能够选择插入文本的某些部分,或者至少应该没有任何视觉上的指示.我已经尝试了一些方法,例如以下CSS,但是没有成功.
I need to find a way to prevent users from selecting text in a textarea. The goal is to create a custom keyboard that is used to enter text in the textarea. I want users to be able to click on the textarea to set the caret position (which is already working right now). However, I don't want the users to be able to select certain parts of the inserted text, or there should at least be no visual indication of this. I have already tried a few things, such as the following CSS, but without success.
textarea {
-moz-user-select: none;
-webkit-user-select: none;
-khtml-user-select: none;
user-select: none;
}
该解决方案可以使用CSS和/或JavaScript,并且只能在Google Chrome中运行.谢谢!
The solution can be in CSS and/or JavaScript, and it only has to work in Google Chrome. Thanks!
更新:
禁用textarea对我不起作用.如前所述,我希望用户能够通过单击位置将插入号放置在某些位置.如果我禁用文本区域,此功能将丢失.
Disabling the textarea will not work for me. As I mentioned, I want users to be able to place the caret at certain positions by clicking on the location. If I would disable the textarea, this functionality would be lost.
@OPUS:该解决方案不适用于textareas.@andi:是的@Pointy:键盘事件可以被阻止.用户不必使用键盘输入文本,而是使用我在页面上提供的自定义键盘.将其与屏幕键盘进行比较.@downvoters:这个问题有什么不好的?
@OPUS: That solution doesn't work with textareas. @andi: that's right @Pointy: keyboard events can be blocked. Users don't have to enter text with their keyboard, but with a custom keyboard that I offer on the page. Compare it with an on-screen keyboard. @downvoters: What's so bad about this question?
推荐答案
只读"属性和用户选择"属性的组合有效.
A combination of the "readonly" property and "user-select" property works.
第二条规则禁用select上突出显示的边框,这是一种视觉选择.
The 2nd rule disables the highlighted border on select, which is a kind of visual selection.
"unselectable"属性似乎是Opera/IE特有的.
The "unselectable" property seems to be Opera/IE specific.
样式:
.noselect {
cursor: default;
-webkit-user-select: none;
-webkit-touch-callout: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
}
.noselect:focus {
outline: none;
}
标记:
<textarea class="noselect" readonly="readonly" unselectable="on"></textarea>
只读可能比禁用更合适(在发生点击事件时,仍可以使用JS切换).
read-only might be more suitable than disabled (one can still toggle with JS, upon click event).
这篇关于在文本区域中禁用文本选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!