我尝试了一些方法,但没有一个奏效。有人知道绕过这个的妙招吗?
<textarea placeholder='This is a line \n this should be a new line'></textarea>
<textarea placeholder='This is a line
should this be a new line?'></textarea> <!-- this works in chrome apparently -->
更新:它不工作在chrome。它只是textarea的宽度。
参见:http://jsfiddle.net/pdXRx/
我不喜欢隐藏占位符当你聚焦文本区域。所以我做了一个构造函数占位符,看起来完全像内置占位符,也工作在其他浏览器比谷歌Chrome。它非常方便,因为你可以随时使用占位符函数,甚至不需要jQuery。
编辑:
它现在还能正确处理特殊情况,比如插入占位符。
var textarea = document.getElementById("textarea");
new Placeholder(textarea, "Line 1\nLine 2\nLine 3");
function Placeholder(el, placeholder) {
if (el.value == "" || el.value == placeholder) {
el.style.color = "gray";
el.value = placeholder;
el._plc = true;
el.className += " unselectable";
}
function keyPress(e) {
window.setTimeout(function() {
var replaced = reverseStr(el.value).replace(reverseStr(placeholder), "");
if (el.value == "") {
el.value = placeholder;
el.style.color = "gray";
cursorToStart(el);
el._plc = true;
el.className += " unselectable";
} else if (el._plc && el.value.endsWith(placeholder) && replaced !== "") {
el.value = reverseStr(replaced);
el.style.color = "black";
el._plc = false;
el.readOnly = false;
el.className = el.className.replace("unselectable", "");
} else if (el._plc && el.readOnly) {
var ch = String.fromCharCode(e.charCode);
if (e.keyCode == 13) ch = "\n"; // ENTER
else if (e.charCode == 0) return; // non-character keys
el.value = ch;
el.style.color = "black";
el._plc = false;
el.readOnly = false;
el.className = el.className.replace("unselectable", "");
}
}, 10);
}
el.addEventListener("keypress", keyPress, false);
el.addEventListener("paste", keyPress, false);
el.addEventListener("cut", keyPress, false);
el.addEventListener("mousedown", function() {
if (el._plc) el.readOnly = true;
}, false);
el.addEventListener("mouseup", function() {
el.readOnly = false;
if (el._plc) cursorToStart(el);
}, false);
function cursorToStart(input) {
if (input.createTextRange) {
var part = input.createTextRange();
part.move("character", 0);
part.select();
} else if (input.setSelectionRange){
input.setSelectionRange(0, 0);
} input.focus();
}
function reverseStr(str) {
if (!str) return "";
return str.split("").reverse().join("");
}
}
textarea {
border: 1px solid gray;
padding: 3px 6px;
font-family: Arial;
font-size: 13px;
transition: .2s;
}
textarea:hover, textarea:focus {
border-color: #2277cc;
}
textarea:focus {
box-shadow: inset 0 0 5px #85B7E9;
}
*.unselectable {
-webkit-user-select: none;
-webkit-touch-callout: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
}
<textarea id="textarea"></textarea>