Bit*_*Bug 1 html javascript 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" />
Run Code Online (Sandbox Code Playgroud)
然后设置样式,使我消失的文字消失(#333).并且当我开始在字段中输入值时,文本为黑色(#000).
CSS
input[type=text] {
color: #333;
}
input[type=text]:focus {
color: #000;
}
Run Code Online (Sandbox Code Playgroud)
一切正常,直到你移动到下一个输入字段.然后,您刚输入值的字段会更改为#333颜色.我可以看到为什么会发生这种情况,但是#000如果输入字段已经输入了值,则无法完全了解如何将值保持为黑色.
在此先感谢您的协助和教育!
HTML5为<input>标记提供了一个方便的属性,该属性placeholder支持此功能的本机支持.
<input type="text" placeholder="Search..." />
Run Code Online (Sandbox Code Playgroud)
所有最新的浏览器都支持这一点,IE9及以下版本不支持.
<label>请注意,占位符属性不是<label>每个输入应具有的标记的替换者,请确保为<input>用户不可见的标记包含标签.
<label for="search">Search</label>
<input id="search" placeholder="Search..." />
Run Code Online (Sandbox Code Playgroud)
以上内容<label>可以隐藏,因此仍然可以使用辅助技术:
label[for=search] {
position:absolute;
left:-9999px;
top:-9999px;
}
Run Code Online (Sandbox Code Playgroud)
这是一个潜在的跨浏览器解决方案,我已将代码移出标记并转移到脚本标记中,然后使用该类placeholder指示何时淡化文本.
HTML
<input name="firstName" type="text" maxlength="40" value="Enter your first name"
class="placeholder" id="my-input" />
Run Code Online (Sandbox Code Playgroud)
CSS
input[type=text].placeholder {
color: #999;
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
input[type=text]我们可以扩展上面的解决方案,input[type=text]通过使用document.getElementsByTagName(),循环遍历和检查type属性来应用于所有element.getAttribute().
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1984 次 |
| 最近记录: |