如何使可编辑 DIV 看起来像文本字段?

我有一个 DIV,其中有 contentEditable=true,所以用户可以编辑它。问题是它看起来不像一个文本字段,所以用户可能不清楚它是否可以编辑。

有没有一种方法,我可以样式的 DIV,使它出现在用户像一个文本输入字段?

180023 次浏览

You can place a TEXTAREA of similar size under your DIV, so the standard control's frame would be visible around div.

It's probably good to set it to be disabled, to prevent accidental focus stealing.

In WebKit, you can do: -webkit-appearance: textarea;

You could go for an inner box shadow:

div[contenteditable=true] {
box-shadow: inset 0px 1px 4px #666;
}

I updated the jsfiddle from Jarish: http://jsfiddle.net/ZevvE/2/

These look the same as their real counterparts in Safari, Chrome, and Firefox. They degrade gracefully and look OK in Opera and IE9, too.

Demo: http://jsfiddle.net/ThinkingStiff/AbKTQ/

CSS:

textarea {
height: 28px;
width: 400px;
}


#textarea {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}


input {
margin-top: 5px;
width: 400px;
}


#input {
-moz-appearance: textfield;
-webkit-appearance: textfield;
background-color: white;
background-color: -moz-field;
border: 1px solid darkgray;
box-shadow: 1px 1px 1px 0 lightgray inset;
font: -moz-field;
font: -webkit-small-control;
margin-top: 5px;
padding: 2px 3px;
width: 398px;
}

HTML:

<textarea>I am a textarea</textarea>
<div id="textarea" contenteditable>I look like textarea</div>


<input value="I am an input" />
<div id="input" contenteditable>I look like an input</div>

Output:

enter image description here

I would suggest this for matching Chrome's style, extended from Jarish's example. Notice the cursor property which previous answers have omitted.

cursor: text;
border: 1px solid #ccc;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 200px;
overflow: auto;
padding: 2px;
resize: both;
-moz-box-shadow: inset 0px 1px 2px #ccc;
-webkit-box-shadow: inset 0px 1px 2px #ccc;
box-shadow: inset 0px 1px 2px #ccc;

The problem with all these is they don't address if the lines of text are long and much wider that the div overflow:auto does not ad a scroll bar that works right. Here is the perfect solution I found:

Create two divs. An inner div that is wide enough to handle the widest line of text and then a smaller outer one which acts at the holder for the inner div:

<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:500px;">
<div style="width:800px;">


now really long text like this can be put in the text area and it will really <br/>
look and act more like a real text area bla bla bla <br/>


</div>
</div>

If you use bootstrap just add form-control class. For example:

class="form-control"