我之前使用过以下内容,我选择使用图像而不是其他任何内容的原因是因为动态添加到输入中的文本可能会导致混淆,并且会妨碍用户进行编辑。使用图像意味着它可以一直存在并且不会妨碍用户输入:
它只是用 jQuery 编写的,因为它到处都是,这可以很容易地用纯 js 重写 - 并且可以很容易地进行优化。
http://jsfiddle.net/pafMg/
CSS:
input {
border: 1px solid black;
background: #fff;
padding: 2px;
}
标记:
<input class="right-aligned" type="text" />
<input class="left-aligned" type="text" />
代码:
在下面的代码中 padding-left 和 padding-right 必须考虑到您使用的图像的宽度。
$(function(){
/* For left aligned additions */
$('input.left-aligned')
.css({
'padding-left': '20px',
'background-image': 'url(/favicon.png)',
'background-position' : '2px center',
'background-repeat': 'no-repeat'
});
});
左对齐的版本非常简单,但是右对齐变得有点复杂:
$(function(){
/* For right aligned additions */
$('input.right-aligned')
.bind('keypress keyup', function(e){
var input = $(this), measure, text = input.val(), x, w, y;
/// You can calculate text width, but it's not easily cross-browser
/// easier method, inject the text to a span and measure that instead
if ( !input.data('measure') ){
/// only build our measuring span the first time
measure = $('<span />')
.hide() // hide it
.appendTo('body')
/// try and match our span to our input font
/// this could be improved
.css({
'font-weight':input.css('font-weight'),
'font-family':input.css('font-family'),
'font-size':input.css('font-size')
});
/// store the measure element for later
input.data('measure', measure );
}
/// handle if the user types white space
text = text
.replace(/\s/g,' ')
.replace(/</g,'>');
measure = input.data('measure');
measure.html(text);
w = measure.width();
y = input.width();
/// calculate the image position (minus padding)
x = w + parseInt(input.css('padding-left')) + 2;
/// take into account the scroll ability of an input
x -= ( w > y ? w - y : 0 );
/// reposition our image background on the input
input
.css({
'padding-right': '20px',
'background-image': 'url(/favicon.png)',
'background-position' : x + 'px center',
'background-repeat': 'no-repeat'
});
}).trigger('keyup');
});