[html/css/js]搜索建议提示v1.0
效果图:
代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>search advice</title><style type="text/css">body {font-family:"yaHei Consolas Hybrid";margin:0;}ul {margin:0;list-style:none;padding:0;}/*搜索栏*/.search-block {width:400px;position:relative;margin:50px auto;}.search-block input {font-size:20px;}/*提示标签*/.lbl-default {position:absolute;cursor:text;top:15px;left:15px;color:#ccc;}/*输入框*/.txt-default {width:378px;height:28px;border:1px solid #ddd;padding:10px;}/*按钮*/.btn {border:0;width:100px;height:50px;background-color:#56bdf3;color:#fff;text-align:center;cursor:pointer;}/*搜索按钮*/.search-button {position:absolute;left:300px;top:0;}/*搜索建议*/.search-advice {display:none;width:400px;position:absolute;background-color:#fff;}/*搜索建议列表*/#search-advice-list {border-left:1px solid #ddd;border-right:1px solid #ddd;border-bottom:1px solid #ddd;}#search-advice-list li{display:block;width:378px;height:30px;padding:10px;}#search-advice-list li:hover {background-color:#f5f5f5;}</style><script type="text/javascript">// 搜索建议模拟数据var mockData = ['jsp','json','ajax','java','jquery','java','javascript'];// 根据id获取dom元素function $(id) {return document.getElementById(id);}// 隐藏dom元素function hide(dom) {dom.style.display = 'none';}// 显示dom元素function show(dom) {dom.style.display = 'block';}// 将label绑定到input上作为输入提示function bindLabelToInput(labelId, inputId) {// 获取输入焦点时,隐藏提示标签$(inputId).onfocus = function() {hide($(labelId));};// 失去输入焦点时,判断输入框的是否有值,有则显示提示标签$(inputId).onblur = function() {if (this.value == null || this.value.length < 1) {show($(labelId));}};}function createDomTo(tagName,arr,parentNode) {for (var i=0; i<arr.length; i++) {var tag = document.createElement(tagName);tag.innerHTML = arr[i];parentNode.appendChild(tag);}}// 窗口加载完dom结构时window.onload = function() {bindLabelToInput('lbl-search','txt-search');// 搜索建议var adviceWords = new Array();var ul = $('search-advice-list');// 建议列表$('txt-search').onkeyup = function() {if (this.value.length > 0) {for (var i=0; i<mockData.length; i++) {if (mockData[i].indexOf(this.value) >= 0) {adviceWords.push(mockData[i]);}}// 有结果才显示提示框if (adviceWords.length > 0) {ul.innerHTML = '';createDomTo('li',adviceWords,ul);show(ul.parentNode);}adviceWords = new Array();//清空建议数据} else {hide(ul.parentNode);}};};</script></head><body><div class="search-block"> <label for="txt-search" id="lbl-search" class="lbl-default">请输入要搜索的内容</label> <input type="text" id="txt-search" class="txt-default"/> <input type="button" id="submit-button" class="btn search-button" value="搜索"/> <div class="search-advice"><ul id="search-advice-list"></ul> </div> </div></body></html>