js文本框提示和自动完成

简介:   1.模仿大型网站自动提示,就是输入“苹果”,在水果类中搜索,html代码如下:   js代码如下: //显示搜索下拉选择项 function showTips(searchInput) { var top = searchInput.

 

 

1.模仿大型网站自动提示,就是输入“苹果”,在水果类中搜索,html代码如下:

 

<div  id="searchTips" style="display:none;width:291px;height:auto;position:absolute;z-index:9001;">
    <ul></ul>
    <input type="hidden" id="hidSearchOption" />
</div>


js代码如下:

    //显示搜索下拉选择项
    function showTips(searchInput) {
        var top = searchInput.offsetTop+32;
        var left = searchInput.offsetLeft;
        var width = searchInput.offsetWidth;
        var ulStringFormat = "<li onclick='selectOption(this)' onmouseover='javascript:this.style.backgroundColor=\"#A9A9A9\"' onmouseout='javascript:this.style.backgroundColor=\"#666666\"'  style='width:220px;height:25px;background-color: #666666;display:block;'><span style='float:left;text-indent:6px'>" + $("#searchvalue").val() + "</span><span id='{0}' style='float:right;padding-right:1px;fond-size:10px;'>{1}</span></li>";
        while (searchInput = searchInput.offsetParent) {
            top += searchInput.offsetTop;
            left += searchInput.offsetLeft;
        }
        if ($("#searchvalue").val().length > 0) {
            $("#searchTips").css({ "left": left + "px", "top": top + "px" }).show();
            $("#searchTips>ul").empty().append(kendo.format(ulStringFormat, "sFlightNo","航班号")).append(kendo.format(ulStringFormat, "sTailNo", "机号"));
        }
        else {
            searchInputBlur();
        }
    }
    function fillvalue(value) {
        alert($(value).find("span:first").html());
        searchInputBlur();
    }
    function searchInputBlur() {
        $("#searchTips").hide();
    }
    function selectOption(li) {
        $("#hidSearchOption").val(($(li).find("span:last").attr("id")));
        searchInputBlur();
    }
    //搜索
    function searchContent() {
        var url = "/Manager/DutyManager?BeginTime=" + getTodayBeginUTCTime() + "&EndTime=" + getTodayEndUTCTime()
        var option = $("#hidSearchOption").val();
        var value = $("#searchvalue").val().trim();
        switch (option) {
            case "sFlightNo":
                url += "&FlightNo=" + value;
                break;
            case "sTailNo":
                url += "&TailNo=" + value;
            default:
        }
        openWindow(url);
    }

效果图如下

 

 2.带上下左右键的

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SimulateUpDownKeySelect.html</title>
    <style type="text/css">
        #divSelect {border:1px solid red; width:208px !important;width:210px;}
        #divSelect ul {width:200px;margin:3px; margin-left:-35px;*margin-left:3px;overflow:hidden}
        #divSelect ul li {float:left; list-style-type:none;width:45px;height:14px;line-height:20px;font:14px arial;text-align:center;padding:2px}
        #divSelect li:hover {background :green;cursor:pointer}
        #txtInput {width:205px;}
    </style>
</head>
<body>
    <form method="post" action="##">
    <input type="text" id="txtInput" value="" autocomplete="off" onkeydown="if(event.keyCode==13)return false;" />
    <!--
防止回车键触发表单提交
onKeyPress
-->
    <div id="divSelect">
    </div>
    <script type="text/javascript">
        var list = "<ul>"
        list += "<li>123a</li><li>战争片</li><li>动作片</li><li>爱情片</li><li>剧情片</li><li>记录片</li><li>fbac</li><li>bbca</li><li>defe</li><li>gzza</li><li>恐怖片</li><li>古装片</li><li>电视剧</li><li>读书</li><li >小说</li><li>作品集</li><li>历史</li><li>诗歌</li><li >散文</li><li>军事</li>";
        list += "</ul>"
        document.getElementById('divSelect').innerHTML = list;
    </script>
    </form>
    <script type="text/javascript">
        function $(sId) {
            return document.getElementById(sId);
        }
        function clearSelectedOptBgColor(target) {
            if (target.seletedIndex >= 0)
                target.options[target.seletedIndex].style.background = "";
        }
        function setSelectedOptBgColor(target) {
            target.options[target.seletedIndex].style.background = "green";
        }
        var upKeyCode = 38;
        var downKeyCode = 40;
        var enterKeyCode = 13;
        var oInput = $("txtInput");
        oInput.options = $("divSelect").getElementsByTagName("li");
        oInput.seletedIndex = -1;
        oInput.focus();
        //oInput.onKeyPress{}
        oInput.onkeyup = function (event) {
            if (event == undefined)
                event = window.event;
            switch (event.keyCode) {
                case 37:
                    clearSelectedOptBgColor(this);
                    this.seletedIndex--;
                    if (this.seletedIndex < 0)
                        this.seletedIndex = this.options.length - 1;
                    this.value = this.options[this.seletedIndex].innerHTML;
                    setSelectedOptBgColor(this);

                    break;
                case 38:
                    clearSelectedOptBgColor(this);
                    this.seletedIndex = this.seletedIndex - 4;
                    if (this.seletedIndex < 0)
                        this.seletedIndex = this.options.length - 1;
                    this.value = this.options[this.seletedIndex].innerHTML;
                    setSelectedOptBgColor(this);

                    break;
                case 39:
                    clearSelectedOptBgColor(this);
                    this.seletedIndex++;
                    if (this.seletedIndex >= this.options.length)
                        this.seletedIndex = 0;
                    this.value = this.options[this.seletedIndex].innerHTML;
                    setSelectedOptBgColor(this);
                    break;
                case 40:
                    clearSelectedOptBgColor(this);
                    this.seletedIndex = this.seletedIndex + 4;
                    if (this.seletedIndex >= this.options.length)
                        this.seletedIndex = 0;
                    this.value = this.options[this.seletedIndex].innerHTML;
                    setSelectedOptBgColor(this);
                    break;
                case enterKeyCode:
                    this.value = this.options[this.seletedIndex].innerHTML;
                    //alert('aa')
                    break;
            }
        };
        oInput.onblur = function () {
            clearSelectedOptBgColor(this);
            this.seletedIndex = 1;
        };
    </script>
</body>
</html>

效果:

 

3.下面这个只带上下键提示,写的比较规范

<head>
    <title></title>
    <style type="text/css">
        #autoCompleteWp
        {
            border: 1px solid #ddd;
            padding: 20px;
            margin: 100px auto;
            width: 300px;
            position: relative;
        }
        #datalist
        {
            position: absolute;
            left: 0;
            top: 56px;
            background: #f8f8f8;
            z-index: 2;
            border: 1px solid #FCC;
            padding: 15px;
            display: none;
        }
        #datalist li
        {
            line-height: 1.6;
            list-style: none;
            cursor: pointer;
        }
        .on
        {
            background: #06C;
            color: #fff;
        }
    </style>
</head>
<body>
    <div id="autoCompleteWp">
        请输入邮箱:<br />
        <input id="autoComplete" type="text" />
        <ul id="datalist">
        </ul>
    </div>
        <script type="text/javascript">
            var $ = function (id) {
                return "string" == typeof id ? document.getElementById(id) : id;
            };
            var Class = {
                create: function () {
                    return function () { this.initialize.apply(this, arguments); }
                }
            }
            function addEventHandler(oTarget, sEventType, fnHandler) {
                if (oTarget.addEventListener) {
                    oTarget.addEventListener(sEventType, fnHandler, false);
                } else if (oTarget.attachEvent) {
                    oTarget.attachEvent("on" + sEventType, fnHandler);
                } else {
                    oTarget["on" + sEventType] = fnHandler;
                }
            };
            function removeEventHandler(oTarget, sEventType, fnHandler) {
                if (oTarget.removeEventListener) {
                    oTarget.removeEventListener(sEventType, fnHandler, false);
                } else if (oTarget.detachEvent) {
                    oTarget.detachEvent("on" + sEventType, fnHandler);
                } else {
                    oTarget["on" + sEventType] = null;
                }
            }
            String.prototype.trim = function () {
                return this.replace(/^\s+|\s+$/g, '');
            }
            //自动完成类
            var autoComplete = Class.create();
            autoComplete.prototype = {

                initialize: function (obj, databox, data) {
                    _this = this;
                    this.input = $(obj);
                    this.data = data;
                    this.index = 0;
                    this.datalist = $(databox).getElementsByTagName('li');
                    addEventHandler(this.input, 'keyup', this.writting);
                },
                writting: function (e) {
                    var e = e || window.event;
                    var keyCode = e.keyCode || e.charCode;  //兼容ie firefox等事件

                    switch (keyCode) {

                        case 38: //
                            _this.index--;
                            if (_this.index < 0) {
                                _this.index = $('datalist').getElementsByTagName('li').length - 1
                            }

                            if ($('datalist').getElementsByTagName('li').length > 0) {

                                for (var k = 0; k < $('datalist').getElementsByTagName('li').length; k++) {
                                    $('datalist').getElementsByTagName('li')[k].className = ''
                                }
                            }
                            $('datalist').getElementsByTagName('li')[_this.index].className = "on";
                            break;
                        case 40:
                            _this.index++;
                            if (_this.index > $('datalist').getElementsByTagName('li').length - 1) {
                                _this.index = 0;
                            }
                            if ($('datalist').getElementsByTagName('li').length > 0) {
                                for (var k = 0; k < $('datalist').getElementsByTagName('li').length; k++) {
                                    $('datalist').getElementsByTagName('li')[k].className = ''
                                }
                            }
                            $('datalist').getElementsByTagName('li')[_this.index].className = "on"
                            break;
                        //回车         
                        case 13:
                            _this.input.value = $('datalist').getElementsByTagName('li')[_this.index].innerHTML.replace(/<\/?strong>/gi, '')  //获取html,正则过滤标签,只取其值
                            $('datalist').style.display = 'none'
                            break;
                        default:
                            var temp = [];
                            var val = _this.input.value.trim();
                            if (val == '') {
                                $('datalist').style.display = 'none'
                                return;
                            }
                            //如果输入字符包含\会导致正则表达式出错,转换成\\即可  [ ] 等也需要转义
                            if (val.indexOf('\\') != -1) {
                                val = val.replace(/\\/g, '\\\\')
                            }
                            var reg = new RegExp('^(' + val + ')');
                            //利用正则把匹配到的数据 加入数组
                            for (var i = 0; i < _this.data.length; i++) {
                                //如果匹配到
                                if (reg.test(_this.data[i])) {
                                    thedata = _this.data[i].replace(reg, '<strong>$1</strong>'); //利用js正则式中replace中的占位符特性
                                    temp.push('<li title="' + i + '">' + thedata + '</li>')
                                }
                                else {
                                    $('datalist').style.display = 'none'
                                }
                            }
                            //如果匹配到数据
                            if (temp.length > 0) {
                                $('datalist').innerHTML = temp.join('');
                                $('datalist').style.display = 'block';
                                var li = $('datalist').getElementsByTagName('li');
                                li[0].className = "on";
                                _this.index = 0;
                                for (var i = 0; i < li.length; i++) {
                                    li[i].onmouseover = function () {
                                        for (var i = 0; i < li.length; i++) {
                                            li[i].className = '';
                                        }
                                        this.className = 'on';
                                        _this.index = this.getAttribute('title');
                                    }
                                    //鼠标点击
                                    li[i].onclick = function () {
                                        _this.input.value = this.innerHTML.replace(/<\/?strong>/gi, '')  //获取html,正则过滤标签,只取其值
                                        $('datalist').style.display = 'none'
                                    }
                                }
                            }
                            else {
                                $('datalist').innerHTML = '';
                            }
                            break;
                    }
                }
            }
            var data = ['yaofjaa@vip.qq.com', 'yaojaa008@163.com', 'yaojaa@yahoo.com', 'yaoj4aa@sohu.com.com', 'yaojaa@vipf.qq.com', 'yfaojaa@163.com', 'yaojfaa@sina.com', 'yaojaa@yahoo.com', 'yaojaa@sohu.com']
            var auto = new autoComplete('autoComplete', 'datalist', data)
    </script>
</body>
</html>

效果如下:

 

 

作者:Tyler Ning
出处:http://www.cnblogs.com/tylerdonet/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,如有问题,可以通过以下邮箱地址williamningdong@gmail.com  联系我,非常感谢。

目录
相关文章
|
存储 JSON JavaScript
【2023-08-20】最新PDF.js PDF批注注释插件库:创建、保存和管理PDF注释批注(高亮、文本框、绘图、截屏、历史记录、橡皮檫)-pdf.js
探索基于pdf.js-dist开发的纯Javascript PDF批注插件库,支持保存、导出、导入和管理PDF文件中的批注。多个功能模块为您提供丰富的PDF注释体验。
598 0
【2023-08-20】最新PDF.js PDF批注注释插件库:创建、保存和管理PDF注释批注(高亮、文本框、绘图、截屏、历史记录、橡皮檫)-pdf.js
|
4月前
|
JavaScript 前端开发
使用js对文本框设置字数限制
使用js对文本框设置字数限制
72 0
|
6月前
|
JavaScript
【干货】JS 限制input文本框输入
【干货】JS 限制input文本框输入
|
7月前
|
JSON 前端开发 JavaScript
【2024-04-22 源码】最新PDF批注注释插件库,pdf.js插件库,纯前端离线JavaScript库(PDF高亮、下划线、橡皮擦、文本框、画笔、历史记录)
一款基于 pdf.js 开发的PDF批注插件库,支持纯离线内网部署,功能完善、强大且在不断升级,极易上手,欢迎关注!
202 4
【2024-04-22 源码】最新PDF批注注释插件库,pdf.js插件库,纯前端离线JavaScript库(PDF高亮、下划线、橡皮擦、文本框、画笔、历史记录)
|
7月前
|
JavaScript 前端开发 索引
用JavaScript精巧地实现文本框的粘贴功能:一次成功的尝试
前言:本文实际是用js移动控制光标的位置!解决了网上没有可靠教程的现状 废话连篇 默认情况对一个文本框粘贴,应该会有这样的功能: 粘贴文本后,光标不会回到所有文本的最后位置,而是在粘贴的文本之后 将选中的文字替换成粘贴的文本
84 1
|
JavaScript UED
利用js复制文本框里面的内容到剪切板,并且隐藏文本框
利用js复制文本框里面的内容到剪切板,并且隐藏文本框
301 0