<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文本框提示文字示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
background-color: #f5f5f5;
}
.container {
max-width: 500px;
margin: 0 auto;
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
color: #333;
font-size: 24px;
margin-bottom: 20px;
}
.input-group {
margin-bottom: 20px;
}
.input-group label {
display: block;
margin-bottom: 8px;
font-weight: bold;
}
.input-group input {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
.input-group input.placeholder {
color: #999;
}
.footer {
margin-top: 30px;
font-size: 12px;
color: #888;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h1>用户信息填写</h1>
<div class="input-group">
<label for="username">用户名</label>
<input type="text" id="username" class="placeholder" value="请输入您的用户名">
</div>
<div class="input-group">
<label for="email">电子邮箱</label>
<input type="text" id="email" class="placeholder" value="请输入您的电子邮箱">
</div>
<div class="footer">
</div>
</div>
<script>
$(document).ready(function() {
// 获取所有带有placeholder类的输入框
var $inputs = $('input.placeholder');
// 为每个输入框添加点击事件
$inputs.on('focus', function() {
var $this = $(this);
// 如果当前值是提示文字,则清空
if ($this.hasClass('placeholder')) {
$this.val('').removeClass('placeholder');
}
});
// 失去焦点时,如果内容为空,则恢复提示文字
$inputs.on('blur', function() {
var $this = $(this);
if ($this.val() === '') {
// 根据输入框的id设置不同的提示文字
var placeholderText = '';
if ($this.attr('id') === 'username') {
placeholderText = '请输入您的用户名';
} else if ($this.attr('id') === 'email') {
placeholderText = '请输入您的电子邮箱';
}
$this.val(placeholderText).addClass('placeholder');
}
});
// 表单提交时,检查是否还包含提示文字
$('form').on('submit', function() {
$inputs.each(function() {
if ($(this).hasClass('placeholder')) {
$(this).val('');
}
});
});
// 页面加载时自动触发blur事件,确保空输入框显示提示文字
$inputs.trigger('blur');
});
</script>
</body>
</html>
1394

被折叠的 条评论
为什么被折叠?



