我有一个带有占位符属性的输入文本字段。占位符在我输入文本时消失,但我希望占位符文本在单击按钮“清除”或文本字段为空后重新出现。我有什么办法可以做到这一点?
下面是我下面的代码。我试过了
document.text.value = "hello";但是当我开始打字时,文字"hello“就会留在框里。
HTML
<input type="text" placeholder="hello">
<input type="button" value="clear" onclick(clearText)>Javascript
function(clearText) {
document.text.value = " ";
}发布于 2015-02-05 02:59:52
当文本字段为空时,占位符将自动重新出现。
单击clear按钮时,可以在按钮上使用onclick属性,并按如下方式定义函数:
使用纯JS实现:
<script>
function clearText() {
// we use getElementById method to select the text input and than change its value to an empty string
document.getElementById("my_text").value = "";
}
</script>
<!-- we add an id to the text input so we can select it from clearText method -->
<input id="my_text" type="text" placeholder="hello">
<!-- we use onclick attribute to call the clearText method -->
<input type="button" value="clear" onclick="clearText();">或者您可以使用jQuery:
<script>
function clearText() {
$("#my_text").val("");
}
</script>
<input id="my_text" type="text" placeholder="hello">
<input type="button" value="clear" onclick="clearText();">发布于 2015-02-05 03:01:55
最简单的方法是:
<input placeholder="hello" onchange="if (this.value == '') {this.placeholder = 'hello';}"
/>
发布于 2015-02-05 03:03:08
你很亲密
HTML:
<input type="text" id='theText' placeholder="hello">
<input type="button" value="clear" onclick='clearText()'>JavaScript:
clearText = function(){
document.getElementById('theText').value = "";
}https://stackoverflow.com/questions/28335382
复制相似问题