鬼文本 - 如何在文本框中隐藏文本

l--*_*''' 15 html javascript css

我有一个在线表格:

http://yoursdproperty.com/index.php?option=com_chronocontact&Itemid=56

我希望在那里有一些微弱的灰色文本,以便当用户点击它时,它会消失

就像在这个StackOverflow表单中一样,问题的标题是"你的编程问题是什么,是描述性的?"

实现这个的最简单方法是什么?

Mic*_*rdt 28

在HTML5中,这可以通过placeholder属性轻松实现- 不知道现在支持的范围有多广.


Sam*_*son 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";
  }
}
Run Code Online (Sandbox Code Playgroud)