文本背景的CSS在文本输入元素

fei*_*pet 7 html css

想知道这是否可行:

假设我有一个文本输入元素,我想用它来输入货币.可能我想在文本输入之前使用前缀来指示用户正在执行输入的货币.

因此,HTML看起来像:

US$ <input type="text" />
Run Code Online (Sandbox Code Playgroud)

但是,让我们说,我想要的"US $"上面显示为一个前缀的文本输入本身,而"US $"是输入字符串的一部分.像"US $"这样的地方是文本输入的背景文本.当然,文本输入将缩进以避免与背景文本冲突.

没有使用图像或Javascript的任何方式来实现这一点?

谢谢!

Ted*_*und 8

我没有时间在IE中尝试我的解决方案(现在就开始工作),但如果你愿意的话你可以玩这个:http://pastie.org/581472

更新:快速浏览一下IE6-8,它在其中任何一个都没有用.不确定它是否是最小HTML5文档或其他原因的原因,我将在今天或明天稍后再看一下.

更新2:更新了代码以使用FF 3.5,Opera 9,Safari 4,IE6-8(可能更多和更早版本,但未经过测试).获取更新的代码.

<!doctype html>
<title>Background text inside text input control</title>

<style>
    form { position: relative; }
    input { background: transparent; position: relative; text-indent: 28px; z-index: 2; }
    span { color: #999; font-size: 14px; left: 5px; position: absolute; top: 3px; z-index: 1; }
</style>

<form action="" method="post">
    <input type="text">
    <span>US$</span>
</form>
Run Code Online (Sandbox Code Playgroud)

更新的代码:

<!doctype html>
<html lang="en">
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Background text inside text input control</title>
    <style>
        form { position: relative; }
        input { padding-left: 28px; }
        span { color: #999; font-size: 14px; left: 5px; position: absolute; top: 3px; }
    </style>
  </head>
  <body>
    <form action="" method="post">
      <input type="text">
      <span>US$</span>
    </form>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)