使用 javascript/jquery 将字符修复到文本输入框
我正在寻找一种方法将美元符号 $ 固定到文本输入框,例如 但使其不可能要删除的默认值,以便无论用户输入什么,总是有一个 $ 符号“前置”输入。
干杯
I am looking for a way to 'fix' a dollar symbol $ to a text input box eg <input type="text" value="$" />
but make it not possible for the default value to be removed, so that whatever the user inputs, there is always a $ symbol 'prepending' input.
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
可以使用背景图像,但它很难维护,并且不会对字体大小的变化做出反应,这使得它在我看来不是最佳选择。
我认为更好的方法是:
在输入旁边放置一个
$
(实际上是在它之前)。给它
位置:相对;左:20px
。$ 符号随后移入输入字段。
然后,为输入字段指定
padding-left: 24px
。瞧! $ 符号位于输入字段中,不会遮挡任何内容,并且无法删除。
There is the possibility of a
background-image
but it's difficult to maintain, and doesn't react to font size changes, which makes it the less optimal choice IMO.A better way in my opionion would be:
Put a
<span>$</span>
next to the input (before it, actually).give it
position: relative; left: 20px
.The $ sign then moves into the input field.
Then, give the input field
padding-left: 24px
.Voilá! The $ sign is in the input field, does not obscure anything, and cannot be removed.
扩展 Pekka 的答案,我在我的页面上使用了它,但我使用 jQuery 对其进行了一些自动化。因此,对于这个例子,我想在所有输入字段中放入 $ 符号,我给它们一个“成本”类。
CSS:
jQuery:
这会将带有“cost”类的 Span 放置在输入之前,并且还会在输入和 Span 周围包裹一个 div,因此确保它们位于同一行。
如果您没有 jQuery,可以从以下位置获取: jQuery.com
现在我有一个简单的问题 - 我注意到使用这种样式,在 IE6、7 和 8 中,$ 符号未正确排列。有人能解决这个问题吗?
谢谢你!
Expanding on Pekka's answer, I used this on my page, but I automated it a little bit with jQuery. So for this example, all of the input fields that I want to put a $ symbol in, I give them a class of "cost".
CSS:
jQuery:
This will place the span with a class of "cost" right before your input, and also wrap a div around both the input, and the span, so they are ensured to be on the same line.
If you don't have jQuery, you can get it from: jQuery.com
Now I've got a quick question - I noticed that with this styling, in IE6,7, and 8, the $ symbol is not lined up correctly. Does anybody out there have a fix for this?
Thank you!
这只是视觉效果吗?如果是,您可以使用 CSS 作为输入的背景图像。
然后,在服务器上,您可以对该值执行任何您想要的操作(例如在其前面加上 $)。
Is this as a visual effect only? If yes you could apply that with CSS as a background image on the input.
Afterwards, on the server, you can do whatever you want with the value (e.g prepend it with $).
我也一直在寻找不同的解决方案。使用 css 通过填充来缩进文本并在该位置放置背景图像是最好的选择。
I too have been looking at different solutions for this. Using css to indent the text with padding and putting a background image in that position is your best bet.
我是这样做的:
使用
。
如果用户愿意,可以手动删除美元符号。
I did it like this:
with
<input type="text" id="price">
.User can remove the dollar sign manually though if he/she wants to.