jQuery仿百度搜索引擎

项目效果

在这里插入图片描述

在这里插入图片描述

代码

index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<link rel="stylesheet" href="css/searchEngine.css" />
	</head>
	<script src="https://www.jq22.com/jquery/jquery-1.9.1.js"></script>
	<script src="js/searchEngine.js"></script>
	<script src="js/ajaxPackInfo.js"></script>
	<style>
		html,body {
			
			height: 100%;
		}
		.search{
			min-width: 300px;
		}
	</style>
	<body>
		<input type="text" name="search" id="search"/>
		<br/>
		这是搜索引擎<br/>
		引擎数据有:["中国工商", "中国工商银行", "中国建设银行", "中国工商局", "中国银行", "中国工人", "中国大集团",
						"中国华为","abcd","efgh","igklmn","opqrst","uvwsyz"
					]
		<!-- <div class="search">
			<div class="search-input">
				<input type="text" />
			</div>
			<div class="search-show">
				<ul>
					<li>xxx</li>
					<li>xxx</li>
				</ul>
			</div>
		</div> -->

		<script>
			$(function() {
				$("#search").initSearch({placeholder:"请输入中国"});
			});
		</script>
	</body>
</html>

searchEngine.css

.search{
	position: relative;
	min-width: 150px;
}
input:focus{ outline: none; }
.search-input{
	width: 100%;
	border: 2px solid #c4c7ce;
	box-sizing: border-box;
	padding: 5px 10px 5px 10px;
	border-radius: 10px 10px 10px 10px;
	background-color: white;
}
.search-input>input{
	width: 100%;
	height: 25px;
	border: none;
	font-size: 16px;
}
.search-show{
	position: absolute;
	left: 0px;
	z-index: 999;
	width: 100%;
	min-height: 50px;
	box-sizing: border-box;
	padding: 10px 10px 0px 10px;
	background-color: white;
	display: none;
}
.search-show>ul{
	padding: 0px;
	margin: 0px;
	list-style: none;
	font-size: 16px;
}
.search-show>ul>li{
	height: 30px;
	display: flex;
	align-items: center;
}
.search-show>ul>li:hover{
	color: #4e71f2;
}

ajaxPackInfo.js

const L_AJAX=$.extend({
    //ajax封装
    ajaxPack : function(obj,callback,errCallback){
        $.ajax({
            type: obj.type,
            url: `${obj.url}`,
            data: obj.param,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            success : function (res) {
                L_AJAX.ajaxResultReduction(res,callback,errCallback);
            },
            error : function(response, ajaxOptions, thrownError){
                const res={
                    code:500,
                    message:"失败",
                    data:"请求发送错误,请检查网络或联系管理员!",
                };
                L_AJAX.ajaxResultReduction(res,callback,errCallback);
            },
        });
    },

    //ajax结果处理
    ajaxResultReduction : function(res,callback,errCallback){
        let resData=res;
        if (resData.code==undefined){
             resData={
                code:res==null ? 500 : 200,
                data:res==null ? "没有查到数据" :res,
                message: res==null ? "失败:" : "成功",
            };
        }
        L_AJAX.ifAjaxResErr(resData,callback,errCallback);
    },

    //请求结果成功错误返回
    ifAjaxResErr : function (res,callback,errCallback) {
        if (res.code==200){
            callback(res);
        }else {
           let errInfo=res.message+":"+res.data;
            errCallback(res,errInfo);
        }
    }
});

searchEngine.js

(($) => {
	//默认参数
	let defaults = {
		width: "200px",
		height: "35px",
		inpBorderSize: "2px",
		inpBorderColor: "#EEEEEE",
		borderSize: "2px",
		borderColor: "red", //#4e71f2
		placeholder: "搜索",
		borderRadius:"10px",
		static: true,
		paramData: {}
	};
	let settings = null;
	$.fn.extend({
		//初始化
		initSearch(options) {
			if (options != null && options != "") {
				settings = $.extend(defaults, options);
			} else {
				settings = defaults;
			}

			//隐藏原来的输入框
			$(this).css("display", "none");

			//获取原来的输入框的id name
			let inpId = $(this).attr("id");
			let inpName = $(this).attr("name");

			//创建新的输入框
			let input = `<div class="search">
							<div class="search-input">
								<input type="text" id="inp_${inpId}" name="${name}" placeholder="${settings.placeholder}"/>
							</div>
							<div class="search-show div_${inpId}">
								<ul id="ul_${inpId}"></ul>
							</div>
						</div>`;

			//在原来的输入框后面添加新的输入框
			$(this).after(input);

			/* $(`#inp_${inpId}`).css({
				"border-bottom": `${settings.inpBorderSize} solid ${settings.inpborderColor}`,
			}); 

			$(`#inp_${inpId}`).parent().parent().css({
				"min-width": settings.width,
				"border": `${settings.borderSize} solid ${settings.borderColor}`,
			});*/
		
			$(`#inp_${inpId}`).focus(function() {
				$(this).css("border-bottom",
					`${settings.inpBorderSize} solid ${settings.inpBorderColor}`);
					
				$(this).parent().css({
					"border": `${settings.borderSize} solid ${settings.borderColor}`,
					"border-bottom" : "none",
					"border-radius" : `${settings.borderRadius} ${settings.borderRadius} 0px 0px`
				})
				$(this).parent().next().css({
					"display": "block",
					"border": `${settings.borderSize} solid ${settings.borderColor}`,
					"border-top" : "none",
					"border-radius": `0px 0px ${settings.borderRadius} ${settings.borderRadius}`
				});
			});
			
			$(`#inp_${inpId}`).blur(function() {
				$(this).css("border-bottom", "none");
				$(this).parent().css({
					"border": `${settings.borderSize} solid #c4c7ce`,
					"border-radius" : `${settings.borderRadius} ${settings.borderRadius} ${settings.borderRadius} ${settings.borderRadius}`
				})
				
				$(`#ul_${inpId}`).find("li").remove();
				$(this).parent().next().css({
					"display": "none",
					"border": `${settings.borderSize} solid #c4c7ce`,
					"border-top" : "none",
					"border-radius": "0px 0px 0px 0px"
				});
				//$(this).parent().next().css("display", "none");
			});
			
			//注册input 输入监听事件
			$(`#inp_${inpId}`).bind('input propertychange', function() {
				$(`#${inpId}`).val($(`#inp_${inpId}`).val());
				$(`#ul_${inpId}`).find("li").remove();
				if (settings.static) {
					let arr = ["中国工商", "中国工商银行", "中国建设银行", "中国工商局", "中国银行", "中国工人", "中国大集团",
						"中国华为","abcd","efgh","igklmn","opqrst","uvwsyz"
					];
					let val = $(`#inp_${inpId}`).val();
					let len = val.length;

					for (let item of arr) {
						if (item.length >= len && $(`#ul_${inpId}`).find("li").length < 6) {
							let text = item.substring(-1, len);
							let valtext = val.substring(-1, len);
							if (text == valtext) {
								$(`#ul_${inpId}`).append(`
													<li style="cursor: pointer">${item}</li>
												`);
							}
						}
					}
					$(`.div_${inpId}`).css("display", "block");
					//注册li 点击事件
					$(`#ul_${inpId}>li`).mousedown(function(event) {
						let spanText = $(this).html();
						$(`#inp_${inpId}`).val(spanText);
						$(`#${inpId}`).val(spanText);
						$(`.div_${inpId}`).css("display", "none");
						event.stopPropagation(); //  阻止事件冒泡
					});
					$(`#ul_${inpId}>li`).hover(function() {
						$(this).css("color", settings.borderColor);
					}, function() {
						$(this).css("color", "black");
					});
				} else {
					let val = $(`#inp_${inpId}`).val();
					settings.paramData.callback(val);
					L_AJAX.ajaxPack(settings.paramData.param, res => {
						let data = res.data;
						for (let item of data) {
							$(`#ul_${inpId}`).append(`
												<li style="cursor: pointer">${item}</li>
											`);
						}
						$(`.div_${inpId}`).css("display", "block");
						//注册li 点击事件
						$(`#ul_${inpId}>li`).mousedown(function(event) {
							let spanText = $(this).html();
							//console.log(spanText);
							$(`#inp_${inpId}`).val(spanText);
							$(`#${inpId}`).val(spanText);
							$(`.div_${inpId}`).css("display", "none");
							event.stopPropagation(); //  阻止事件冒泡
						});
						$(`#ul_${inpId}>li`).hover(function() {
							$(this).css("color", settings.borderColor);
						}, function() {
							$(this).css("color", "black");
						});
						settings.paramData.succeedCallBack(res);
					}, (res, errInfo) => {
						settings.paramData.errCallBack(res, errInfo);
					})
				}
				
			});
		}
	});
})(jQuery);

转载于:https://www.jq22.com/jquery-info23998

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值