让自己成为一个 jQuery 插件。http://jsfiddle.net/ppuGL/
$.fn.typeOverText = function() {
var $ = jQuery,
$this = $(this);
$this.addClass('type-over');
$this.append('<input type="text" class="type-over-input">');
return $this;
}
一些HTML:
<span class="text">Type over me</span>
调用插件:
$('.text').typeOverText();
还有一些 CSS:
.type-over {
position: relative;
color: #ccc;
display: inline-block;
padding: 5px;
}
.type-over-input {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: transparent;
font-family: inherit;
font-size: inherit;
border: none;
margin: 0;
padding: 0;
padding-left: inherit;
padding-right: inherit;
}
.type-over-input:focus {
outline: 1px solid #ccc;
}
附录
受 brbcoding 的启发,这是另一个纯 CSS 的想法。http://jsfiddle.net/trevordixon/ppuGL/1/
<span data-shadow-text="Type over me">
<input>
</span>
<style>
[data-shadow-text] {
font-family: sans-serif;
font-size: 24px;
position: relative;
padding: 5px;
display: inline-block;
}
[data-shadow-text]:before {
content: attr(data-shadow-text);
position: relative;
color: #ccc;
display: inline-block;
}
[data-shadow-text] input {
position: absolute;
left: 0;
top: 0;
background-color: transparent;
font-family: inherit;
font-size: inherit;
border: none;
margin: 0;
padding: inherit;
padding-left: inherit;
padding-right: inherit;
width: 100%;
}
[data-shadow-text] input:focus {
outline: 1px solid #ccc;
}
</style>