Javascript 鬼文本 - 如何在文本框中有模糊的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2173937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:05:41  来源:igfitidea点击:

ghost text - how to have faint text in textbox

javascripthtmlcss

提问by l--''''''---------''''''''''''

I've an online form:

我有一个在线表格:

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

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

I would like to have some faint gray text there so that when the user clicks on it, it disappears

我想在那里有一些微弱的灰色文本,这样当用户点击它时,它就会消失

exactly like in this StackOverflow form where in the title of the question it says "what's your programming question, be descriptive?"

就像在这个 StackOverflow 表单中一样,在问题的标题中它说“你的编程问题是什么,描述一下?”

what is the simplest way to implement this?

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

回答by Michael Borgwardt

In HTML5, this is achieved very easily via the placeholderattribute - not sure how widely supported that is right now, though.

在 HTML5 中,这可以通过placeholder属性很容易地实现——但不确定目前支持的范围有多广。

回答by Sampson

You made no mention of jQuery, or any other javascript framework, so I'm going to give you the pure Javascript solution.

您没有提及 jQuery 或任何其他 javascript 框架,因此我将向您提供纯 Javascript 解决方案。

Some boolean logic based upon the value of the box to set the font color. When the user clicks the input, if the value is equal to your default value, you erase the contents. If it's not, you do nothing. When the user leaves the box, if the values are empty, add your default text in again.

一些基于框的值的布尔逻辑来设置字体颜色。当用户单击输入时,如果该值等于您的默认值,则删除内容。如果不是,你什么都不做。当用户离开框时,如果值为空,请再次添加您的默认文本。

// 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";
  }
}

回答by SLaks

You can use this jQuery plugin.

你可以使用这个 jQuery 插件