input中加入搜索圖標
阿新 • • 發佈:2018-09-30
box style align dex info amaze 如果 tel 隱藏
1. HTML代碼:
<div class="box">
<label for="q" id="q_label">請輸入關鍵字</label>
<input id="q" type="text">
<i class="am-icon-search search" id="q_i"></i>
</div>
其實結構非常簡單,最外層放一個div盒子,裏面放三個元素:一個label,一個input,一個i標簽。使用for屬性將label與input綁定,label用來顯示字符串,i標簽引入圖標,input幹好本職工作就行了——提供輸入框。我這裏是用的amazeUI框架的圖標,所以用i標簽引入,如果你直接使用圖片,用img當然也沒有問題。
好了,結構搭好了,下面就是css大顯身手的時候了。
2. CSS代碼 :(布局根據自己需要調整)
/**
*放置input的div盒子
*1.此處應我的項目需要,加了些特別的設置,如字體、背景色等,按需添加;
*2.內層input不加邊框,看起來效果會自然一點,所以外層div設置了邊框和圓角
*/
.box{
background-color: #ffffff;
border: 1px solid #eeeeee;
border-radius: 6px;
font-size: 14px;
text-align: center;
}
/* *
*label標簽樣式 放在.box下,不至於影響其他的label
*采取絕對定位,位置根據需求確定
*/
.box label{
z-index: 2;
position: absolute;
left: 50%;
margin-left: -8%;
color: #B2B2B2;
top: 4.8rem;
font-weight: normal;
}
/**
*input標簽樣式
*寬度適應外層div
*隱藏邊框
*這裏有個小技巧,height與line-height值相等,可保證文字垂直居中;但我發現文字比圖標略偏下,進行了微調;
*/
.box input{
text-indent: 10px;
height: 1.8rem;
line-height: 1.9rem;
width: 100%;
border: none;
outline: none;
}
/**
*圖標樣式
*絕對定位,自定義顏色
*/
.box i{
position: absolute;
top: 4.8rem;
left: 50%;
margin-left: -15%;
color: #B2B2B2;
}
3. JS代碼:
/**
* js判斷input輸入框中是否有值,以此來判斷是否隱藏默認提示信息
* 使用keyup事件
*/
$(function() {
$(‘#q‘).on(‘keyup‘,function() {
var len = document.getElementById(‘q‘).value;
if(len == ‘‘){
$(‘#q_label‘).show();
$(‘#q_i‘).show();
}else{
$(‘#q_label‘).hide();
$(‘#q_i‘).hide();
}
});
})
效果圖如下:
input中加入搜索圖標