仿微信的搜索功能
使用weui来开发基于微信公众号,weui地址:https://weui.shanliwawa.top/index.html
input的type设置为search,而且外面要用form表单包围,这样再移动端弹起软键盘的时候,才能显示搜索,不然一般是换行
<form class="weui-search-bar__form" action="javascript:return true;"> <div class="weui-search-bar__box"> <i class="weui-icon-search"></i> <input class="weui-search-bar__input" id="searchInput" @focus="focusfns()" placeholder="请输入搜索内容" type="search" /> <a href="javascript:" class="weui-icon-clear" id="searchClear"></a> </div> <label class="weui-search-bar__label" id="searchText" style="transform-origin: 0px 0px 0px; opacity: 1; transform: scale(1, 1);" > <i class="weui-icon-search"></i> <span id="serach_size">请输入搜索内容</span> </label> </form>
$(function() {
var $searchBar = $("#searchBar"),
$searchResult = $("#searchResult"),
$searchText = $("#searchText"),
$searchInput = $("#searchInput"),
$searchClear = $("#searchClear"),
$searchCancel = $("#searchCancel");
function hideSearchResult() {
$searchResult.hide();
$searchInput.val("");
}
function cancelSearch() {
hideSearchResult();
$searchBar.removeClass("weui-search-bar_focusing");
$searchText.show();
$("#searchTemplate").hide();
}
$("form.weui-search-bar__form").submit(function() {
//提交需要做的事情
});
$("#searchInput").bind("input propertychange", function() {
let searchContent = $("#searchInput")
.val()
.trim();
if (searchContent == "") {
$("#searchResult").hide();
$("#searchTemplate").show();
}
});
$searchText.on("click", function() {
$searchBar.addClass("weui-search-bar_focusing");
$searchInput.focus();
});
$searchClear.on("click", function() {
hideSearchResult();
$("#searchTemplate").show();
$searchInput.focus();
});
$searchCancel.on("click", function() {
cancelSearch();
$searchInput.blur();
});
});
注意:form表单有自动提交功能的,所以设置action:javascript:return true;,虽然语法上不合理,但是没有关系,这个只是控制台报错。
而且之前我使用click绑定事件,然后返回false,例如:
<form class="weui-search-bar__form" @click="onClick()">
...
</form>
function onClick(){
return fasle;
}
但是出现ios弹出软键盘之后,输入文字,不显示搜索字体而且电脑端enter键不会搜索,所以最终采用
action:javascript:return true;解决。