如何更改onfocus和onblur的输入值(无jquery)

时间:2012-11-05 00:55:09

标签: javascript search focus field placeholder

我写了一些代码,有点像使用JavaScript的HTML5占位符的替代品,但它不起作用。据我所知(我对js的平庸知识),一切都应该有效,但事实并非如此。请帮忙!!!这是我的代码:

的JavaScript:

(function(){
    var field = document.getElementById('placeholder');
    var placeholdertext = "Search box"; // << change this to whatever you want the placeholder text to be

    field.setAttribute("onblur", "if(value=='') { value = '" + placeholdertext + "'")
    field.setAttribute("onfocus", "if(value=='" + placeholdertext + "') { value = '' }")
})(); 

HTML

<input type="search" value="Search box" id="placeholder">

编辑:

我不想使用jQuery或inline-html-coding。谢谢你的帮助,伙计!!!

4 个答案:

答案 0 :(得分:2)

value替换为代码中的this.value(因为您需要检查触发事件的元素的值,而不是某些全局变量)并且will work

作为旁注,或许我更喜欢在这里使用placeholder属性,仅为不支持它的浏览器提供JS填充。这也会简化javascript代码部分,因为您不必使用某些变量来存储一些与DOM相关的数据:

field.onblur = function() {
  if (this.value === '') {
    this.value = this.getAttribute('placeholder');
  }
};

field.onfocus = function() {
  if (this.value === this.getAttribute('placeholder') ) {
    this.value = '';
  }
};

...事实上,我更倾向于使用addEventListener/attachEvent而不是onblur/onfocus,如this answer中所述。

答案 1 :(得分:1)

没有jQuery:

field.onblur = function() {
  if (field.value == '') {
    field.value = placeholdertext;
  }
};

field.onfocus= function() {
  if (field.value == placeholdertext ) {
    field.value = '';
  }
};

答案 2 :(得分:1)

<input type="text" value="Enter The User Name" onblur="if(this.value == '') { this.style.color='#f00'; this.value='Enter The User Name'}" onfocus="if (this.value == 'Enter The User Name') {this.style.color='#000'; this.value=''}" />

在没有Jquery的情况下试试这个

答案 3 :(得分:0)

我没有对此进行测试,但如果我理解你的问题,这应该可行。如果它有效,请不要忘记点击复选标记。

    var field = document.getElementById('placeholder');
    var placeholdertext = "Search box";

    field.bind('onblur', function() {
        if (field.text() === '') {
            field.text(placeholdertext);
        }
    });

    field.bind('onfocus', function() {
        if (field.text() === '') {
            field.text(placeholdertext);
        }
    });