javascript - 如何在 <input> 元素内创建标签并为其设置样式?

标签 javascript html css placeholder textinput

我可以在输入元素中制作我的标签(我的“消失的文本”):

HTML

<input name="firstName" type="text" maxlength="40" value="Enter your first name"
 onfocus="if(this.value==this.defaultValue)this.value=''" 
 onblur="if(this.value=='')this.value=this.defaultValue" />

然后设置它的样式,使我消失的文本变淡(#333)。并设置样式,以便当我开始向字段中输入值时,文本为黑色 (#000)。

CSS

input[type=text] {
    color: #333;
}
input[type=text]:focus {
    color: #000;
}

一切正常,直到您移至下一个输入字段。然后您刚刚输入值的字段变回 #333 颜色。我明白为什么会发生这种情况,但无法完全了解如何在输入字段中输入值时将值保持为黑色 #000 颜色。

在此先感谢您的帮助和教育!

最佳答案

HTML5

HTML5 为 <input> 带来了一个方便的属性标签名为 placeholder这使得 native 支持此功能。

jsFiddle

<input type="text" placeholder="Search..." />

支持

所有最新的浏览器都支持这个,IE9 and below don't however .

<label>

请注意 placeholder attribute is not a replacemenr for the <label> tag每个输入都应该有,确保为 <input> 添加标签即使它对用户不可见。

<label for="search">Search</label>
<input id="search" placeholder="Search..." />

以上<label>可以隐藏,因此它仍然可用于辅助技术,如下所示:

label[for=search] {
    position:absolute;
    left:-9999px;
    top:-9999px;
}

跨浏览器解决方案

这是一个潜在的跨浏览器解决方案,我已将代码从标签中移出并放入脚本标签中,然后使用类 placeholder指示何时淡化文本。

jsFiddle

HTML

<input name="firstName" type="text" maxlength="40" value="Enter your first name" 
    class="placeholder" id="my-input" />

CSS

input[type=text].placeholder {
    color: #999;
}

JS

<script type="text/javascript">
var input = document.getElementById('my-input');

input.onfocus = function () {
    if (this.value == this.defaultValue && this.className == 'placeholder') {
        this.value = '';
    }
    this.className = '';
};
input.onblur = function() {
    if (this.value == '') {
        this.className = 'placeholder';
        this.value = this.defaultValue;
    }
};
</script>

适用于所有input[type=text]

我们可以扩展上述解决方案以适用于所有input[type=text]通过使用 document.getElementsByTagName() ,遍历它们并检查 type属性为 element.getAttribute() .

jsFiddle

var input = document.getElementsByTagName('input');

for (var i = 0; i < input.length; i++) {
    if (input[i].getAttribute('type') === 'text') {
        input[i].onfocus = inputOnfocus;
        input[i].onblur = inputOnblur;
    }
}
function inputOnfocus () {
    if (this.value == this.defaultValue && this.className == 'placeholder') {
        this.value = '';
    }
    this.className = '';
}
function inputOnblur() {
    if (this.value == '') {
        this.className = 'placeholder';
        this.value = this.defaultValue;
    }
}

关于javascript - 如何在 &lt;input&gt; 元素内创建标签并为其设置样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15672970/

相关文章:

javascript - Three.js BufferGeometry 与粒子几何

javascript - 空 Web 应用程序在 Enter 上发回

javascript - 当模态背景不存在时,允许人们单击 Bootstrap 模态下的链接

html - 如何使用登录创建导航栏 | bootstrap 4 中的注册按钮?

javascript - 我的混合应用程序在检查包含字符串的 li 元素时不会更改页面

javascript - 在javascript中手动对数组进行排序

javascript - 使用内置样式的 Bootstrap 3 表单验证

javascript - Chrome 中的 HTML 表格分页符打印

javascript - scrollspy 导航到不同的页面并返回同一位置

css - 如何将 CSS 样式表应用于 XULRunner 中的所有页面 View