js 实现placeholder
使用HTML5原生属性实现placeholder
在HTML5中,<input>和<textarea>元素原生支持placeholder属性,无需JavaScript即可实现占位文本效果:
<input type="text" placeholder="请输入内容">
<textarea placeholder="请输入多行文本"></textarea>
兼容旧浏览器的JavaScript实现
对于不支持HTML5 placeholder的旧浏览器(如IE8及以下),可通过以下JavaScript方案模拟:
function simulatePlaceholder(inputElement) {
if (!inputElement.placeholder) return;
const placeholderText = inputElement.placeholder;
inputElement.value = placeholderText;
inputElement.setAttribute('data-original-color', inputElement.style.color);
inputElement.style.color = '#999';
inputElement.addEventListener('focus', function() {
if (this.value === placeholderText) {
this.value = '';
this.style.color = this.getAttribute('data-original-color') || '';
}
});
inputElement.addEventListener('blur', function() {
if (this.value === '') {
this.value = placeholderText;
this.style.color = '#999';
}
});
}
// 对所有input和textarea元素应用
document.querySelectorAll('input, textarea').forEach(simulatePlaceholder);
使用CSS伪类增强样式
现代浏览器支持:placeholder-shown伪类,可单独设置placeholder的样式:

input:placeholder-shown, textarea:placeholder-shown {
color: #999;
font-style: italic;
}
/* 兼容前缀 */
input:-moz-placeholder, textarea:-moz-placeholder {
color: #999;
}
input::-moz-placeholder, textarea::-moz-placeholder {
color: #999;
}
input:-ms-input-placeholder, textarea:-ms-input-placeholder {
color: #999;
}
第三方库解决方案
使用现成的polyfill库如jQuery插件或standalone库:
-
jQuery方案:

$('input, textarea').placeholder(); -
独立库placeholder.js:
<script src="placeholder.js"></script> <script> Placeholder.init(); </script>
表单验证时的注意事项
提交表单时需要清除模拟的placeholder值:
document.querySelector('form').addEventListener('submit', function() {
document.querySelectorAll('input, textarea').forEach(function(el) {
if (el.value === el.placeholder) {
el.value = '';
}
});
});
动态内容处理
对于动态添加的表单元素,需要重新初始化:
function initPlaceholders() {
document.querySelectorAll('input, textarea').forEach(function(el) {
if (!el.getAttribute('data-placeholder-bound')) {
simulatePlaceholder(el);
el.setAttribute('data-placeholder-bound', 'true');
}
});
}
// 监听DOM变化
const observer = new MutationObserver(initPlaceholders);
observer.observe(document.body, { childList: true, subtree: true });






