可选择但不可编辑的 html 文本字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14479423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:11:32  来源:igfitidea点击:

Selectable but not editable html text field

htmlinput

提问by tasomaniac

I am working on a mobile website and I have a text input field.

我在一个移动网站上工作,我有一个文本输入字段。

I want it to be selected and copiable but not editable. When I add readonlyor onfocus="this.blur()"it becomes unselectable. How can I achieve this?

我希望它被选中和复制但不可编辑。当我添加readonlyonfocus="this.blur()"它变得不可选择时。我怎样才能做到这一点?

回答by Krzysztof Jab?oński

Check this out.

看一下这个。

<textarea rows="10" cols="50" onclick="this.focus();this.select()" readonly="readonly">
    example text
</textarea>

Edit:

编辑:

You can reassign text input value everytime it changes by adding input listener.

您可以通过添加输入侦听器在每次更改时重新分配文本输入值。

var inp = $("input")[0]; // select the input with proper selector
var default_value = inp.value;

inp.addEventListener("input", function () { 
    this.value = default_value;
}, false);

Working jsfiddle here.

在这里工作jsfiddle