javascript - 在搜索框中为 Onfocus 事件添加字体颜色

标签 javascript html

如何在我的搜索框中添加默认值的颜色和字体。

<input type="text" name="q" value="Enter your keywords here"    
onfocus="if (this.value == 'Enter your keywords here') {this.value = '';}" onblur="if (this.value   == '') {this.value = 'Enter your keywords here';}"
onwebkitspeechchange = "this.value = this.value.replace('Enter your keywords here','')";
x-webkit-speech style="left:9px;top:4px;position:relative;background-color:#fafafa;border:1px     solid;color:#333;font-size:1.4em;width:400px;height:28px"; />

最佳答案

您可以设置输入框的默认样式,然后在onfocus和onblur事件上更改颜色,如下所示:

<input type="text" name="q" value="Enter your keywords here"    
    onfocus="if (this.value == 'Enter your keywords here') {
        this.value = ''; 
        this.style.color = '#000';
    }" 
    onblur="if (this.value == '') {
        this.value = 'Enter your keywords here'; 
        this.style.color = '#CCC';
    }"
    onwebkitspeechchange = "this.value = this.value.replace('Enter your keywords here','')";
    x-webkit-speech 
    style="left:9px;top:4px;position:relative;background-color:#fafafa;border:1px solid; color:#CCC;font-size:1.4em;width:400px;height:28px"; 
/>

而且您绝对应该考虑将此事件代码放在一个单独的脚本中,以使您的代码看起来更简洁。

您还可以查看此 fiddle 以获得更简洁的代码。 http://jsfiddle.net/MXpSw/

关于javascript - 在搜索框中为 Onfocus 事件添加字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10859977/

相关文章:

javascript - 反复倒计时

javascript - window.location.hash 不会在 IE 的 iframe 中提醒

javascript - 将 HTML 放入 Javascript 源中还是使用 AJAX 检索 HTML?

html - TD 宽度不随输入字段改变

javascript - Div 不完全等于具有继承值的父 div 的高度

javascript - 为什么Javascript的instanceof对这些原生构造函数返回true?

javascript - 未捕获的类型错误 : Cannot call a class as a function in react and redux

javascript - 使用 JQuery 提交简单表单并对必填字段进行限制?

Javascript 生成 html 元素以从特定主机名加载资源

javascript - 我有一个不断改变高度的 div。如何让第二个 div 不断采用第一个 div 的高度?