如何有文本已经在输入和关闭时的焦点

How to have text already in the input and off when on focus?

本文关键字:焦点 输入 文本      更新时间:2023-09-26

请查看下面的jsfiddle链接:

http://jsfiddle.net/H49EC/1/

可以看到,它是两个搜索框,下面有一个按钮。我怎么能有它,所以文本是在每个框,但当每个框点击文本消失?

同样,如果单击该框但没有输入任何内容,则文本将重新出现。

谢谢大家,我一直在搜索,但我不确定这是什么,或者需要使用什么语言。

再次感谢!

詹姆斯

在输入中使用占位符属性。

<input type='text' placeholder='whatever' />

如果你使用HTML5,你可以使用新的placeholder=""属性:

placeholder="Your text here"
http://jsfiddle.net/H49EC/2/


如果你不使用HTML5,你可以使用jQuery更改值:(适用于较旧的浏览器和IE)

$('input').focus(function(){        
            // on focus if the value of the field is still the initial then clear it        
            if ( (this.value) == this.defaultValue ) this.value = '';    }).blur(function(){        
            // on blur if the value is still cleared then restore the initial        
            if ( (this.value) == '' )   this.value = this.defaultValue;    })    
http://jsfiddle.net/H49EC/7/

如果你需要支持旧的浏览器并且不能使用HTML5 placeholder属性,你将需要使用JavaScript。下面这些内容应该可以帮助您开始:

var input = document.getElementById("input1");
input.onfocus = function() {
    if(this.value === "Default") {
        this.value = "";  
    }
};
input.onblur = function() {
    if(this.value === "") {
        this.value = "Default"; 
    }  
};

这里有一个更新的小提琴,向您展示它是如何工作的。请注意,我已经向input元素添加了id,因此可以使用getElementById访问它。如果你想将它应用于多个输入元素,你可能想要将它一般化,而不是只应用于一个元素。

我曾经在一个页面上使用infieldlabel来完成这个任务,它运行得很好。然而,它是一个jQuery插件。

你的意思是占位符吗?http://jsfiddle.net/H49EC/4/

此链接提供对占位符属性的支持。

目前还不能完全跨浏览器兼容,IE是主要问题。

http://davidwalsh.name/html5-placeholder-css

对于IE,人们在他们上面做div,当你点击它隐藏。在google上输入占位符有很多选择:)

希望这对你有帮助!

占位符就是你要找的。

<input type="text" name="searchText" placeholder="Search Here!" />

有关占位符属性的信息,请参阅W3Schools。

这里是一个快速的jsFiddle