body中
<body> 请输入搜索内容:<input type="text" name="name" value="" id="txt" style="border:1px solid gray;margin:0;padding:0; width:200px;" /></body>
<script>中
<script type="text/javascript">window.onload = function () {var keyWords = {"aaaa": ["a开头", "aa开头", "aaa开头", "aaaa开头"],"bbb": ["b开头", "bb开头", "bbb开头", "bbbb开头"],"aa33": ["杨利伟", "杨振宇", "杨过"],"bbbb111": ["杨忠科", "杨忠学", "杨忠爱国"]};//onchange事件--这个事件不太合适//加一个计时器//===js高级中 会有一个全新方法 做这个题setInterval(function () {document.getElementById('txt').onchange();}, 100);document.getElementById('txt').onchange = function () {//获取文本框的内容var content = this.value;//判断这个内容 是否在键值对中for (var key in keyWords) {if (document.getElementById('dv')) {document.body.removeChild(document.getElementById('dv'));}//如果键值对中有这个keyif (keyWords[content]) {//如果文本框的内容在字典中存在则创建层,创建p标签,p标签添加到层中,层添加到body中//如果body中有个层就删除了var dvObj = document.createElement('div');dvObj.id = 'dv';dvObj.style.width = '200px';//层的高度不用设置//dvObj.style.height = '50px';dvObj.style.border = '1px solid green';dvObj.style.position = 'absolute';dvObj.style.left = this.offsetLeft + 'px';dvObj.style.top = this.offsetTop + this.offsetHeight + 'px';//根据value创建标签添加到层中for (var i = 0; i < keyWords[content].length; i++) {var pObj = document.createElement('p'); //创建p标签pObj.innerHTML = keyWords[content][i];pObj.style.margin = '0';pObj.style.cursor = 'pointer';pObj.onmouseover = function () {this.style.backgroundColor = 'yellow';};pObj.onmouseout = function () {this.style.backgroundColor = '';};dvObj.appendChild(pObj); //p添加到层中 }//层添加到body中 document.body.appendChild(dvObj);}}};};</script>
效果