【问题标题】:How do I style the placeholder text inside a field?如何在字段中设置占位符文本的样式?
【发布时间】:2011-04-28 03:55:27
【问题描述】:

我有这个 jquery 代码来处理两个输入字段的占位符文本的逻辑:

$(document).ready(function() {

$("form input.link").attr("value", "Media Link Here (optional)");
$("form input.email").attr("value", "*Email Address Here");

$("form input.link").live("focus", function() {
    if ( $(this).val() == "Media Link Here (optional)"){
    $(this).val("");
  }
});

$("form input.email").live("focus", function() {
    if ( $(this).val() == "*Email Address Here"){
    $(this).val("");
  }
});

$("form input.link").live("focusout", function() {
    if ( $(this).val() == "" ){
    $(this).attr("value", "Media Link Here (optional)");
  }
}); 

$("form input.email").live("focusout", function() {
    if ( $(this).val() == "" ){
    $(this).attr("value", "*Email Address Here");
  }
});

});

我想设置占位符文本的样式,使其与用户在字段中键入的文本具有不同的样式。我该怎么做?

【问题讨论】:

    标签: jquery css forms


    【解决方案1】:

    编辑: 误读了问题,并认为您使用的是占位符 html 属性。现在我看到你不是,应该在这里使用其他答案,但我会留下我的答案,以防你想使用占位符属性。

    占位符样式尚未广泛实施,因此您必须使用供应商前缀属性:

    ::-webkit-input-placeholder {
        color: red;
    }
    
    :-moz-placeholder {
        color: red;
    }
    

    HERE 是一篇关于占位符的 css 选择器的好文章,它在不同的浏览器中被采用。

    干杯

    【讨论】:

      【解决方案2】:

      给文本框一个特殊的类,它在focus() 上消失,如果没有内容,则在blur() 上添加。

      .placeholder {
        color: gray;
        font-style: italic;
      }
      
      $('.box').focus(function() {
        if (this has default text) {
          $(this).val('');
          $(this).removeClass('placeholder');
        }
      });
      

      并在用户blurs 且文字为默认时添加类。

      【讨论】:

        【解决方案3】:

        你试过了吗……

        $("form input.email").live("focus", function() {
        if ( $(this).val() == "*Email Address Here"){
        $(this).css("cssvalueyouwant", "value you want to set");  //set to normal
        $(this).val("");  }});
        $("form input.email").live("focusout", function() {
            if ( $(this).val() == "" ){
            $(this).attr("value", "*Email Address Here");
            $(this).css("cssvalueyouwant", "value you want to set");   //set to special
        }});
        

        【讨论】:

          猜你喜欢
          • 2012-03-08
          • 1970-01-01
          • 2016-11-24
          • 2015-03-18
          • 2021-10-22
          • 1970-01-01
          • 2018-05-28
          • 2017-09-16
          • 2020-10-12
          相关资源
          最近更新 更多