幽灵文本 - 如何在文本框中显示淡色文本

17
3个回答

30
在HTML5中,这可以通过placeholder属性非常轻松地实现 - 不确定目前有多广泛的支持。

非常感谢!它得到了广泛的支持,但是Firefox和Chrome支持它,对我来说已经足够了。 - Alex Gordon

5
你没有提到jQuery或其他JavaScript框架,因此我将为您提供纯JavaScript解决方案。
根据框中的值设置字体颜色的布尔逻辑。当用户单击输入时,如果该值等于默认值,则擦除内容。如果不是,则不执行任何操作。当用户离开框时,如果值为空,请再次添加默认文本。
// Reference our element
var txtContent  = document.getElementById("content");
// Set our default text
var defaultText = "Please enter a value.";

// Set default state of input
txtContent.value = defaultText;
txtContent.style.color = "#CCC";

// Apply onfocus logic
txtContent.onfocus = function() {
  // If the current value is our default value
  if (this.value == defaultText) {
    // clear it and set the text color to black
    this.value = "";
    this.style.color = "#000";
  }
}

// Apply onblur logic
txtContent.onblur = function() {
  // If the current value is empty
  if (this.value == "") {
    // set it to our default value and lighten the color
    this.value = defaultText;
    this.style.color = "#CCC";
  }
}

不,你不能仅使用HTML完成这个。 - sourcenouveau

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接