单击时会清除文本

时间:2011-11-12 17:08:11

标签: javascript jquery html css textinput

我想知道如何在发布问题时实现类似堆栈溢出的内容:“至少有一个标记,例如(css html asp.net),最多5个标记。

如何在html中为文本输入实现这样的内容,它会部分褪色,但是当您键入时,它不会显示,也不会褪色。

我不介意怎么做,只要它有效。

感谢。

4 个答案:

答案 0 :(得分:7)

最简单的选择是使用placeholder属性:

<input type="text" placeholder="At least one tag, such as 'html', 'asp.net', max five tags." />

JS Fiddle demo

如果要求交叉兼容性,那么JavaScript也是一个选项:

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

for (i=0; i<inputs.length; i++){
    if (inputs[i].hasAttribute('data-hint')){
        inputs[i].value = inputs[i].getAttribute('data-hint');
            inputs[i].style.color = '#999';

        inputs[i].onclick = function(){
            this.value = '';
        };
        inputs[i].onblur = function(){
            if (this.value == '' || this.value == this.getAttribute('data-hint')){
                this.value = this.getAttribute('data-hint');
                this.style.color = '#000';
            }
        };
    }
}

JS Fiddle demo

或者,使用jQuery:

$('input:text').each(
    function(){
        $(this).val($(this).attr('data-hint'));
            $(this).css('color','#999');
    }).click(
    function(){
        $(this).val('');
            $(this).css('color','#000');
    }).blur(
    function(){
        if ($(this).val() == ''){
            $(this).val($(this).attr('data-hint'));
            $(this).css('color','#999');
        }
    });

JS Fiddle demo

参考文献:

Vanilla JavaScript:

jQuery的:

答案 1 :(得分:5)

<input type="text" name="booga" placeholder="This is default text" />

答案 2 :(得分:4)

<input type="text" placeholder="Your text here" />

需要最新的浏览器,但不使用任何类型的代码。

答案 3 :(得分:2)

<input type="text" placeholder="Default text goes here..."/>

正如@ Kolink的回答所解释的那样,这样做需要一个最新的浏览器,但根本不使用代码。