select 下拉框和下拉列表美化
阿新 • • 發佈:2019-02-13
(function($){
var selects=$('select');//獲取select
for(var i=0;i<selects.length;i++){
createSelect(selects[i],i);
}
function createSelect(select_container,index){
//建立select容器,class為select_box,插入到select標籤前
var tag_select=$('<div></div>');//div相當於select標籤
tag_select.attr('class' ,'select_box');
tag_select.insertBefore(select_container);
//顯示框class為select_showbox,插入到建立的tag_select中
var select_showbox=$('<div></div>');//顯示框
select_showbox.css('cursor','pointer').attr('class','select_showbox').appendTo(tag_select);
//建立option容器,class為select_option,插入到建立的tag_select中
var ul_option=$('<ul></ul>');//建立option列表
ul_option.attr('class','select_option');
ul_option.appendTo(tag_select);
createOptions(index,ul_option);//建立option
//點選顯示框
tag_select.toggle(function(){
ul_option.show();
},function(){
ul_option.hide();
});
var li_option=ul_option.find('li');
li_option.on('click',function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).text();
select_showbox.text(value);
ul_option.hide();
});
li_option.hover(function(){
$(this).addClass('hover').siblings().removeClass('hover');
},function(){
li_option.removeClass('hover');
});
}
function createOptions(index,ul_list){
//獲取被選中的元素並將其值賦值到顯示框中
var options=selects.eq(index).find('option'),
selected_option=options.filter(':selected'),
selected_index=selected_option.index(),
showbox=ul_list.prev();
showbox.text(selected_option.text());
//為每個option建立個li並賦值
for(var n=0;n<options.length;n++){
var tag_option=$('<li></li>'),//li相當於option
txt_option=options.eq(n).text();
tag_option.text(txt_option).css('cursor','pointer').appendTo(ul_list);
//為被選中的元素新增class為selected
if(n==selected_index){
tag_option.attr('class','selected');
}
}
}
})(jQuery)