最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make HTML Input Area Readonly but Selectable - Stack Overflow

programmeradmin1浏览0评论

I've got an input area that's transparent and when you click on it the glowing border shows up (intended) and you can edit the text. I'm trying to get the glowing border to still show up when you click it but make the text inside uneditable.

<input style='border:none; background:none;' value='TEXT'>  

Adding readonly or readonly="readonly" makes the input act like an uneditable div, you can't double click the input area to select it all and the glowing border doesn't show up. How can I retain the input functionality without allowing the text to be changed?

I've got an input area that's transparent and when you click on it the glowing border shows up (intended) and you can edit the text. I'm trying to get the glowing border to still show up when you click it but make the text inside uneditable.

<input style='border:none; background:none;' value='TEXT'>  

Adding readonly or readonly="readonly" makes the input act like an uneditable div, you can't double click the input area to select it all and the glowing border doesn't show up. How can I retain the input functionality without allowing the text to be changed?

Share Improve this question asked Jul 1, 2016 at 15:52 CrizlyCrizly 1,0091 gold badge14 silver badges33 bronze badges 1
  • What exactly does selectable mean? That you can select it? Copy it? That it shows a background on focus? – Richard Hamilton Commented Jul 1, 2016 at 15:59
Add a ment  | 

2 Answers 2

Reset to default 6

You can use the readonly attribute with some CSS:

input:focus {
    box-shadow: 0 0 2px 2px #3d94db;
}
<input style='border:none; background:none;' value='TEXT' readonly> 

Maybe give a default value to an input field

The default protocol when a user presses a key is to type in text. We can override that with preventDefault().

Now, I just realized that you can circumvent this by using the mouse right click event. So another event listener is required contextmenu. Now, you can no longer cheat with this.

var inputField = document.getElementById("input-field");

inputField.addEventListener("keydown", function(event) {
    event.preventDefault();
});

inputField.addEventListener("contextmenu", function(event) {
    event.preventDefault();
});
<input type="text" id="input-field" value="This value can be selected" />

发布评论

评论列表(0)

  1. 暂无评论