<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>百度搜索</title>
<style>
#box{
position: absolute;
left: 50%;
margin-left: -200px;
top: 200px;
}
#txt{
width: 300px;
height: 20px;
}
</style>
</head>
<body>
<div id="box">
<input type="text" id="txt" value="">
<input type="button" value="搜索" id="btn">
</div>
<script src="../案例分析/common.js"></script>
<script>
function $(id) {
return document.getElementById(id)
}
//设置元素的文本内容 ,element为任意元素 ,text为任意文本内容
// function setInnerText(element,text) {
// if(typeof element.textContent === 'undefined'){
// element.innerText = text;
// }else{
// element.textContent = text;
// }
//
// }
var keywords = ['胡哥小浪漫','清除我','夏至未至','小样的一切',
'缝纫下u先','凡人修仙传','胡哥','胡歌','呼吁','胡戈','胡下'
];
//获取文本框的注册键盘抬起事件
$('txt').onkeyup = function () {
//每一次键盘抬起都判断页面中有没有这个div
if($('dv')){
//有进行删除
$('box').removeChild($('dv'));//因为会重新进行创建
}
//获取文本框输入的内容
var text = this.value;
var tempArr = [];//临时数组--空数组--存放对应的数据
//把文本框的输入的内容与数组中的每个数据进行对比
for(var i=0;i<keywords.length;i++){
if(keywords[i].indexOf(text) === 0){ //判断每个字符串的第一个字符是否与输入的字串相同
tempArr.push(keywords[i]); //把字符串进行追加到数组当中
}
}
console.log(tempArr.length);
console.log(tempArr);
//遍历临时数组,创建div
//如果临时数组和文本框是空的,不用创建div
if(this.value.length === 0||tempArr.length ===0){ //当文本框什么都没有,而且临时数组也为空
//如果页面中有div,删除div
if($('dv')){ //判断页面中是否有这个div
$('box').removeChild($('dv'));
}
return;//由于这是函数,用return 后面的事件不再继续进行
}
var objDiv = document.createElement('div');
$('box').appendChild(objDiv);//把div加入到box
objDiv.id = 'dv';
objDiv.style.width = '300px';
//objDiv.style.height = '200px';
objDiv.style.border = '1px green solid';
//循环遍历临时数组,创建对应的p标签
for(var i=0;i<tempArr.length;i++){
var pObj = document.createElement('p');
objDiv.appendChild(pObj);
setInnerText(pObj,tempArr[i]);//给p标签加入文本内容
pObj.style.margin = '0';
pObj.style.padding = '0';
pObj.style.cursor = 'pointer';
pObj.style.marginTop = '5px';
pObj.style.marginLeft = '5px';
//createDiv();
//鼠标进入
pObj.onmouseover = function () {
this.style.backgroundColor = 'red';
}
//鼠标移出
pObj.onmouseout = function () {
this.style.backgroundColor = ''
}
}
}
</script>
</body>
</html>
百度搜索案例
猜你喜欢
转载自blog.csdn.net/weixin_42355871/article/details/84839421
今日推荐
周排行