如何在焦点上显示/隐藏输入值?

Mic*_*ski 5 javascript forms input show hide

我在整个网络上看到了这一点,但是想知道是否有人使用EASIEST方式的JavaScript代码来显示模糊的输入值,但隐藏在焦点上.

JLG*_*cia 17

这总对我有用:

<input 
    type="text" 
    value="Name:"
    name="visitors_name" 
    onblur="if(value=='') value = 'Name:'" 
    onfocus="if(value=='Name:') value = ''"
 />
Run Code Online (Sandbox Code Playgroud)


小智 17

由于这仍然出现在谷歌上,我想指出,使用HTML 5,你可以使用带有输入的占位符属性来实现这一点.

<input type="text" id="myinput" placeholder="search..." />
Run Code Online (Sandbox Code Playgroud)

现在,占位符在现代浏览器中是标准的,因此这确实是首选方法.


Mil*_*ros 7

我更喜欢jQuery方式:

$(function(){
    /* Hide form input values on focus*/ 
    $('input:text').each(function(){
        var txtval = $(this).val();
        $(this).focus(function(){
            if($(this).val() == txtval){
                $(this).val('')
            }
        });
        $(this).blur(function(){
            if($(this).val() == ""){
                $(this).val(txtval);
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

它被修改隐藏表格输入值焦点使用 Zack Perdue的jQuery.


Fre*_*örk 5

我所知道的最简单的方法如下:

<input 
    name="tb" 
    type="text" 
    value="some text"
    onblur="if (this.value=='') this.value = 'some text'" 
    onfocus="if (this.value=='some text') this.value = ''"  /> 
Run Code Online (Sandbox Code Playgroud)


Jur*_*uri 0

这就是我在博客上使用的。只要去那里查看后面的源代码即可。

function displaySearchText(text){
    var searchField = document.getElementById('searchField');
    if(searchField != null)
        searchField.value = text;
}
Run Code Online (Sandbox Code Playgroud)

您的输入字段应如下所示:

<input id='searchField' name='q' onblur='displaySearchText("Search...");' onfocus='displaySearchText("");' onkeydown='performSearch(e);' type='text' value='Search...'/>
Run Code Online (Sandbox Code Playgroud)