js模拟select控件

这里写图片描述

思路:
设置一个select容器,把select放在里面并且设置隐藏,放置一个存放选中的文本值,使用ul列表代替option。当列表元素触发click的时候设置对应的option设置选中,并且给select设置value

此次项目select控件是cms生成出来的从前端无法调整样式,所以只能考虑使用js模拟,代码匆忙中完成并未精简,如有更好的方案,还原共同讨论。

案例地址:
http://build2.baiwanx.com.cn/shtzwl201804111782/wsmxztz/index_145.html


具体代码:
HTML结构

<div class="select">
    <span class="placeholder">我是卖家</span>
    <select id="18444" name="18444">
             <option value="">==请选择==</option>
             <option value="我是卖家">我是卖家</option>
             <option value="我是买家">我是买家</option>
        </select>
    <dl class="dl"></dl>
</div>


js代码

$('.select').each(function(){
   var placeholder = $(this).find(".placeholder"),
       list = $(this).find(".dl"),
       select = $(this).find("select"),
       item = select.find("option"),
       str = '';

   //获取select的列表组合作为ul的列表
   item.not(item.first()).each(function(i){
      str += "<dd value='" + $(this).attr("value") + "'>" + $(this).text() + "</dd>"
   });
   list.html(str);

   //初始化select
   placeholder.text(list.find("dd:first").text());
   item.eq(1).attr("selected","selected");
   select.attr("value",list.find("dd:first").attr("value"));
});

//绑定click事件
$('.select').on('click', '.placeholder', function(e) {
    var parent = $(this).closest('.select');
    if (!parent.hasClass('is-open')) {
        parent.addClass('is-open');
        $('.select.is-open').not(parent).removeClass('is-open');
    } else {
        parent.removeClass('is-open');
    }
    e.stopPropagation();
}).on('click', 'dl>dd', function() {  //列表绑定click事件
    var parent = $(this).closest('.select'),
        select = parent.find("select"),
        i = $(this).index();

    parent.removeClass('is-open')
          .find('.placeholder')
          .text($(this).text())
          .attr("value",$(this).attr("value"));

    select.attr("value",$(this).attr("value"));
    select.find("option").eq(i+1).attr("selected","selected");
});

$('body').on('click', function() {
    $('.select.is-open').removeClass('is-open');
});

猜你喜欢

转载自blog.csdn.net/bigbear00007/article/details/80455024