【问题标题】:Have text that clears when you click on it当你点击它时,文本会被清除
【发布时间】:2011-12-27 17:00:37
【问题描述】:

我想知道当您发布问题时如何实现堆栈溢出之类的东西:“至少一个标签,例如(css html asp.net),最多5个标签。

我怎样才能为 html 中的文本输入实现这样的功能,其中它部分褪色,但是当您键入时,它不会显示,也不会褪色。

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

谢谢。

【问题讨论】:

    标签: javascript jquery html css textinput


    【解决方案1】:

    最简单的选择是使用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.

    参考资料:

    原版 JavaScript:

    jQuery:

    【讨论】:

    • 这里要注意两点:1)点击事件实际上应该是焦点。 2)这不关心表单提交。您必须清除服务器端的默认值或处理 onsubmit 事件。
    【解决方案2】:
    <input type="text" name="booga" placeholder="This is default text" />
    

    【讨论】:

      【解决方案3】:
      <input type="text" placeholder="Your text here" />
      

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

      【讨论】:

        【解决方案4】:
        <input type="text" placeholder="Default text goes here..."/>
        

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

        【讨论】:

          猜你喜欢
          • 2020-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多