<input type="text" name="name" value="請輸入2-5個中文名字"
onfocus="if (this.value == '請輸入2-5個中文名字') this.value = ''"
onblur="if (this.value == '') this.value = '請輸入2-5個中文名字'">
缺點:行為與結構耦合、值硬編碼在 HTML 中、無法區分用戶主動輸入同樣文字、密碼框無法顯示提示文本(需切換 type)。
<input type="text" name="name" placeholder="請輸入2-5個中文名字">
<input type="tel" name="tel" placeholder="請輸入您的電話">
<input type="password" name="pwd" placeholder="請輸入密碼">
優勢:
::placeholder { color: #999; opacity: 1; }// 簡易 Polyfill
if (!('placeholder' in document.createElement('input'))) {
$('input[placeholder], textarea[placeholder]').each(function() {
var $this = $(this);
var placeholder = $this.attr('placeholder');
function show() {
if ($this.val() === '') {
$this.val(placeholder).addClass('placeholder');
if ($this.is('[type=password]')) {
// 密碼框需創建鏡像文本框
var $mirror = $this.clone().attr('type', 'text').val(placeholder).addClass('placeholder-mirror');
$this.hide().after($mirror);
$mirror.on('focus', function() {
$mirror.hide();
$this.show().focus();
});
}
}
}
function hide() {
if ($this.hasClass('placeholder')) {
$this.val('').removeClass('placeholder');
}
$this.next('.placeholder-mirror').remove();
$this.show();
}
$this.on('focus', hide).on('blur', show);
show(); // 初始化
});
}
<div class="form-field">
<input type="text" id="name" required>
<label for="name">請輸入2-5個中文名字</label>
</div>
<style>
.form-field { position: relative; margin: 20px 0; }
.form-field input { width: 100%; padding: 10px 0; border: none; border-bottom: 1px solid #ccc; background: transparent; }
.form-field label {
position: absolute; left: 0; top: 10px; color: #999;
transition: all .2s; pointer-events: none;
}
.form-field input:focus + label,
.form-field input:not(:placeholder-shown) + label { /* 需配合 placeholder */
top: -18px; font-size: 12px; color: #3498db;
}
.form-field input:focus { border-bottom-color: #3498db; outline: none; }
</style>
<!-- Vue 3 -->
<script setup>
defineProps(['label', 'type', 'placeholder']);
const props = defineProps({ modelValue: String, emit: ['update:modelValue'] });
const input = ref('');
watch(input, v => emit('update:modelValue', v));
</script>
<template>
<div class="form-field">
<input :type="type" :placeholder="placeholder" v-model="input" @focus="$emit('focus')" @blur="$emit('blur')">
<label>{{ label }}</label>
</div>
</template>
placeholder:零成本、最佳體驗、標準語義。placeholders.js)。onfocus/onblur 硬編碼值、手動切換 type=password/text(安全風險)、重複造輪子。