将默认搜索文本添加到搜索框html

Oti*_*ght 1 javascript search html5 external

我正在努力将"搜索"文本添加到搜索框中.我想要实现:

onfocus:消失的文字

onblur:重新出现文字

到目前为止,我已经实现了这一点,但我不得不将其硬编码为html:

例如.

<input type="text" name="s" id="search-text" size="15" value="Search"  
onfocus="if (this.value==this.defaultValue)
this.value='';" onblur="if(this.value==''){this.value='Search'}">
Run Code Online (Sandbox Code Playgroud)

如果我添加我的.html文件,我得到相同的结果:

例如.

<script type="text/javascript">
var defaultText = "Search...";
var searchBox = document.getElementById("search");

//default text after load
searchBox.value = defaultText;

//on focus behaviour
searchBox.onfocus = function() {
    if (this.value == defaultText) {//clear text field
        this.value = '';
    }
}

//on blur behaviour
searchBox.onblur = function() {
    if (this.value == "") {//restore default text
        this.value = defaultText;
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

(礼貌:http://zenverse.net/javascript-search-box-show-default-text-on-load/)

我想要实现的是在外部.js文件中使用上面的代码,但无论我做什么,我都无法将代码反向链接到我的.html文件中的搜索框.

我很抱歉,如果这是一个糟糕的问题,我已经做了大约10个不同的.html和.js文件交换和重新映射代码,如果没有实际的.html文件中的javascript仍然无法使其工作.

任何帮助将非常感谢谢谢.

Cer*_*rus 12

使用html5占位符属性:

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

这是一个带有输入元素的小提琴.

请注意,在用户自己输入一些文本之前,文本实际上并没有消失.这样,用户将看到更长的提示.