placeholder 属性描述了输入字段的预期值。
在输入值之前,字段中会显示一个简短的提示。
与占位符文本相关的困难之一是使其在焦点上自动隐藏。
在焦点上自动隐藏占位符文本的最简单方法是使用带有 <input> 元素的 onfocus 和 onblur 事件。
如果我们按照以下步骤操作,这很容易。
创建 HTML
- 使用带有 type 属性的 <input> 元素。
- 添加占位符属性。
- 添加 onfocus 和 onblur 事件。
使用 HTML 自动隐藏占位符文本的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
</head>
<body>
<input type="text" placeholder="enter your text"
onfocus="this.placeholder=''"
onblur="this.placeholder='enter your text'" />
</body>
</html>
在下一个示例中,我们使用 :focus 伪类和 ::placeholder 伪元素。
使用 CSS 自动隐藏占位符文本的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
input:focus::placeholder {
color: transparent;
}
</style>
</head>
<body>
<input type="text" placeholder="Enter your text">
</body>
</html>
使用 CSS 和 jQuery 自动隐藏占位符文本的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
li {
padding: 15px;
}
input {
padding: 8px;
}
</style>
</head>
<body>
<form>
<ul class="field-set field-set-stacked">
<li class="field field-text">
<input type="text" placeholder="名字" />
</li>
<li class="field">
<input type="text" placeholder="邮箱地址" />
</li>
<li class="field">
<input type="text" placeholder="电话号码" />
</li>
</ul>
</form>
<script>
$("input")
.each(
function() {
$(this)
.data('holder', $(this)
.attr('placeholder'));
$(this)
.focusin(function() {
$(this)
.attr('placeholder', '');
});
$(this)
.focusout(function() {
$(this)
.attr('placeholder', $(this)
.data('holder'));
});
});
</script>
</body>
</html>
日期:2020-06-02 22:14:57 来源:oir作者:oir
