使用JavaScrip模擬實現(xiàn)仿京東搜索框功能
使用js模擬實現(xiàn)京東的搜索框,主要用了js中的onfocus(注冊焦點事件),onblur(失去焦點的事件);
主要實現(xiàn)了:
- 在鼠標(biāo)點進(jìn)去的時候,里面的默認(rèn)內(nèi)容消失;
- 在輸入之后,再點擊搜索框外,輸入的內(nèi)容還在搜索框中;
- 如果輸入為空,點擊搜索框外,里面自動顯示默認(rèn)內(nèi)容;
- 內(nèi)容顏色的改變
效果圖

代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>京東搜索框</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
border: 0;
}
#search{
width: 550px;
height: 35px;
margin: 100px auto;
}
#search input{
width: 492px;
height: 31px;
border: 2px solid #f10215;
outline-style: none;/* 消除原來的邊框默認(rèn)屬性 */
float: left;
padding-left: 4px;/* 讓文字在搜索的時候距離框4px */
color: #888;
}
#search button{
width: 50px;
height: 35px;
background-color: #f10215;
float: left;
color: white;
}
</style>
<script type="text/javascript">
var keyword = "iphone 11";//搜索框中默認(rèn)的搜索詞
window.onload = function(){
//得到按鈕的對象
var btnsearch = document.getElementById("search").getElementsByTagName("button")[0];
//得到搜索框的對象
var txt = document.getElementById("search").getElementsByTagName("input")[0];
//為搜索框注冊焦點事件
txt.onfocus = function(){
//當(dāng)在焦點上時讓搜索框文字變成黑色
txt.style.color = "black";
//如果搜索框為關(guān)鍵字的時候,注冊焦點就讓搜索框為空
if (txt.value == keyword) {
txt.value = "";
}
}
//為搜索框注冊失去焦點事件
txt.onblur = function(){
//在失去焦點的時候如果搜索框內(nèi)容為空,就讓搜索框顯示默認(rèn)關(guān)鍵字
if (txt.value == "") {
this.value = keyword;
this.style.color = "#888";
}
}
}
</script>
</head>
<body>
<div id="search">
<input type="text" value="iphone 11" />
<button>搜索</button>
</div>
</body>
</html>
- onfocus事件:事件在對象獲得焦點時發(fā)生,常用在表單中
- onblur事件:事件在對象失去焦點時發(fā)生
css中的屬性:outline用于修飾元素的輪廓;
總結(jié)
以上所述是小編給大家介紹的使用JavaScrip模擬實現(xiàn)仿京東搜索框功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
Popup彈出框添加數(shù)據(jù)實現(xiàn)方法
這篇文章主要為大家詳細(xì)介紹了Popup彈出框添加數(shù)據(jù)的簡單實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
深入理解JavaScript創(chuàng)建對象的多種方式以及優(yōu)缺點
本篇文章主要介紹了JavaScript創(chuàng)建對象的多種方式以及優(yōu)缺點,主要介紹了5種方式,有興趣的可以了解下2017-06-06
JavaScript Event事件學(xué)習(xí)第一章 Event介紹
Events是每一個JavaScript程序核心。什么是事件處理,它有什么問題和怎樣寫出跨瀏覽器的代碼,我將在這一章做一個概述。我也會提供一些有精彩的關(guān)于事件處理程序的細(xì)節(jié)的文章。2010-02-02
微信小程序?qū)崿F(xiàn)手風(fēng)琴折疊面板
這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)手風(fēng)琴折疊面板,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05

