Home > Web Front-end > JS Tutorial > body text

jQuery plug-in datalist implements a beautiful input drop-down list_jquery

WBOY
Release: 2016-05-16 15:50:17
Original
1897 people have browsed it

HTML5 defines a nice-looking drop-down list in the input box - datalist. However, its current support is not good (Damn IE, fortunately you will gradually retire...). So I recently wrote a small datalist plug-in based on demand, which is compatible with IE8 (not many people use IE7 anymore, right?). The specific requirements for implementation are as follows:

When selected (triggering blur focus) (whether it is the mouse or the tab key), the input box is cleared and a custom drop-down list is displayed, and then the up and down keys of the keyboard can be used to select (there is no reason why the mouse cannot be used) , click the left mouse button or enter key to input the value of the selected list into the input box.

The specific implementation code is as follows:

HTML

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="robots" content="index, follow" />
<meta name="googlebot" content="index, follow" />
<meta name="author" content="codetker" />
  <title> 表单选中弹出框</title>
<link href="css/reset.css" type="text/css" rel="Stylesheet" /> 
<link href="css/master.css" type="text/css" rel="Stylesheet" /> 

<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
</head>

<body>
  <div class="wrap">
    <form class="center">
      <div class="input_wrap">
        <input name="input1" class="input input1" type="text"/>
        <ul class="input1_ul select_list">
          <li>问题1</li>
          <li>问题2</li>
          <li>问题3</li>
          <li>问题4</li>
          <li>问题5</li>
        </ul>
      </div>
    </form>
  </div>
<script type="text/javascript" src="js/jquery.codetker.datalist.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $(".input_wrap").myDatalist({"bgcolor":"red","widths":1,"heights":1}); 
});
</script>
</body>
</html>

Copy after login

CSS (reset.css is used to initialize browser default values, here is style.css)

.wrap{ margin:0 auto; font-family: "微软雅黑";font-size: 14px;}
.center{ margin: 0 auto; width:500px;}
.input{ margin: 0; padding: 0; /*border:none;*/ width:140px; height: 24px; float:left;}
.select_list{display: none; position:absolute; z-index: 100;}
.select_list li{ height:24px; margin: 0; padding: 0; background-color: #fff; cursor: pointer; list-style: none; position:relative;}
.select_list li:hover{ background-color: red;}
.input_wrap{ position:relative; }

Copy after login

JavaScript

/*
  datalist 0.1 
  自定义datalist插件,实现html5中input元素datalist的效果
  兼容IE8+,Firefox,Chrome等常见浏览器
*/

;(function($,window,document,undefined){ //undefinde是真实的undefined,并非参数
  //将可选择的变量传递给方法

  //定义构造函数
  var Datalist=function(ele,opt){
    this.$element=ele;
    this.defaults={
      'bgcolor':'green',
      'widths':1,
      'heights':1
    },
    this.options=$.extend({}, this.defaults, opt);
  }
  //定义方法
  Datalist.prototype={
    showList:function(){
      var color=this.options.bgcolor;
      var width=this.options.widths;
      var height=this.options.heights; //属性值

      var obj=this.$element; //obj为最外层包裹的div之类的元素,应该拥有positive:relative属性,方便datalist定位。
      var input=$(obj).children().eq(0); //input元素
      var inputUl=$(obj).children().eq(1); //datalist元素
      //设置弹出datalist的大小和样式
      $(inputUl).css({
        "top":$(input).outerHeight()+"px",
        "width":$(input).outerWidth()*width+"px"
      });
      $(inputUl).children().css({
        "width":$(input).outerWidth()*width+"px",
        "height":$(input).outerHeight()*height+"px"
      });

      $(inputUl).children('li').mouseover(function() {
        $(this).css("background-color",color);
        $(this).siblings().css("background-color","#fff");
      });
      $(inputUl).children('li').mouseout(function() {
        $(this).css("background-color","#fff");
      });
      //再次focus变为空,也可以改为某个默认值
      //datalist的显示和隐藏
      $(input).focus(function() {
        if($(this).val()!=""){
          $(this).val("");
        }
        $(inputUl).slideDown(500);

        var n=-1; //记录位置,-1表示未选中。当n=-1时直接按enter浏览器默认为倒数第一个
        $(document).keydown(function(event) {
          /* 点击键盘上下键,datalist变化 */
          stopDefaultAndBubble(event);
          if(event.keyCode==38){//向上按钮
            if(n==0||n==-1){
              n=4;
            }else{
              n--;
            }
            $(inputUl).children('li').eq(n).siblings().mouseout();
            $(inputUl).children('li').eq(n).mouseover();
          }else if(event.keyCode==40){//向上按钮
            if(n==4){
              n=0;
            }else{
              n++;
            }
            $(inputUl).children('li').eq(n).siblings().mouseout();
            $(inputUl).children('li').eq(n).mouseover();
          }else if(event.keyCode==13){//enter键
            $(inputUl).children('li').eq(n).mouseout();
            $(input).val( $(inputUl).children('li').eq(n).text() );
            n=-1;
          }
        });


        //去掉浏览器默认
        function stopDefaultAndBubble(e){
          e=e||window.event;
          //阻止默认行为
          if (e.preventDefault) {
            e.preventDefault();
          }
          e.returnValue=false;

          //阻止冒泡
          if (e.stopPropagation) {
            e.stopPropagation();
          }
          e.cancelBubble=true;
        }

      });
      $(input).blur(function() {
        $(inputUl).slideUp(500);
      });
      $(inputUl).delegate('li', 'click', function() {
          $(input).val( $(this).text() );
      });

      return this;
    }
  }
  //在插件中使用Datalist对象
  $.fn.myDatalist=function(options){
    //创建实体
    var datalist=new Datalist(this,options);
    //调用其方法
    return datalist.showList();
  }
 
})(jQuery,window,document);

Copy after login

Here, the ul li list is used to simulate datalist options. The implementation logic is very simple. What needs to be noted is that div.input_wrap is relatively positioned to facilitate the relative positioning of ul.input1_ul. Since there are many input boxes that do not affect each other, here is input1. Anyway, this is the first plug-in I developed myself, so I’ll mark it.

If you need the code, you can click https://github.com/codetker/myDatalist.

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template