想必很多朋友都知道,<select />、<input type="file" />默认是不能通过样式美化的。前几天在做一个项目的时候恰巧要用到一个select,并想通过样式美化它。于是在博客园里找了一下相关的解决办法,还好找到了一段比较满意的js。经过修改,现在可以兼容各大浏览器,并完全模仿<select />来实现相关功能。
先看看实现的效果:
实现原理:
模访select的外观,用js再构造一个"select"。原始的select html代码如:
原始Html
<!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>
<title></title>
<style type="text/css">
/*global css*/
img{border:0}
ul,li{list-style:none; margin:0; padding:0}
.searchBar{width:590px; height:33px; padding-left:60px; padding-top:7px; margin:40px auto; background:url(images/bg02.gif) no-repeat}
.searchBar .select{float:left; margin-right:8px; display:inline}
.searchBar .text{float:left; margin-right:5px}
.searchBar .text input{width:214px; height:20px; padding-left:4px; line-height:20px; border:1px solid #b7d1eb; color:#aaa}
.btn{vertical-align:middle}
/*---end---*/
/*beautify select box css start*/
.selectbox{width:82px; height:24px; padding-left:4px; line-height:24px; border:none; display:block; cursor:pointer; background:url(images/bg01.gif) no-repeat}
div.selectbox-wrapper{width:63px; border:1px solid #b7d1eb; border-top:none; margin-top:-3px; position:absolute; text-align:left; background-color:#ffffff}
div.selectbox-wrapper ul li{width:59px; padding-left:4px; cursor:pointer; line-height:20px; font-size:12px}
div.selectbox-wrapper ul li.selected{background-color:#e0ecf7}
div.selectbox-wrapper ul li.hover{color:#ffffff; background-color:#36c}
/*---end---*/
</style>
<script src="../js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="js/beautifySelect.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.BeautifySelect(document.getElementById("c"));
});
</script>
</head>
<body>
<div class="searchBar">
<div class="select">
<select id="c" style="display:none" name="c">
<option value="1">生活信息</option>
<option value="2">店铺商家</option>
<option value="3">新闻资讯</option>
<option value="4">团购活动</option>
<option value="5">招聘信息</option>
</select>
</div>
<div class="text">
<input class="s_t" onblur="if(this.value==''){this.value='shuidd.com';this.style.color='#aaa'}"
onfocus="if(this.value=='shuidd.com'){this.value='';this.style.color='#000000'}"
value="shuidd.com" name="keyword"/>
</div>
<a href="#" class="btn"><img src="images/btn.gif" alt=""/></a>
</div>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
/*global css*/
img{border:0}
ul,li{list-style:none; margin:0; padding:0}
.searchBar{width:590px; height:33px; padding-left:60px; padding-top:7px; margin:40px auto; background:url(images/bg02.gif) no-repeat}
.searchBar .select{float:left; margin-right:8px; display:inline}
.searchBar .text{float:left; margin-right:5px}
.searchBar .text input{width:214px; height:20px; padding-left:4px; line-height:20px; border:1px solid #b7d1eb; color:#aaa}
.btn{vertical-align:middle}
/*---end---*/
/*beautify select box css start*/
.selectbox{width:82px; height:24px; padding-left:4px; line-height:24px; border:none; display:block; cursor:pointer; background:url(images/bg01.gif) no-repeat}
div.selectbox-wrapper{width:63px; border:1px solid #b7d1eb; border-top:none; margin-top:-3px; position:absolute; text-align:left; background-color:#ffffff}
div.selectbox-wrapper ul li{width:59px; padding-left:4px; cursor:pointer; line-height:20px; font-size:12px}
div.selectbox-wrapper ul li.selected{background-color:#e0ecf7}
div.selectbox-wrapper ul li.hover{color:#ffffff; background-color:#36c}
/*---end---*/
</style>
<script src="../js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="js/beautifySelect.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.BeautifySelect(document.getElementById("c"));
});
</script>
</head>
<body>
<div class="searchBar">
<div class="select">
<select id="c" style="display:none" name="c">
<option value="1">生活信息</option>
<option value="2">店铺商家</option>
<option value="3">新闻资讯</option>
<option value="4">团购活动</option>
<option value="5">招聘信息</option>
</select>
</div>
<div class="text">
<input class="s_t" onblur="if(this.value==''){this.value='shuidd.com';this.style.color='#aaa'}"
onfocus="if(this.value=='shuidd.com'){this.value='';this.style.color='#000000'}"
value="shuidd.com" name="keyword"/>
</div>
<a href="#" class="btn"><img src="images/btn.gif" alt=""/></a>
</div>
</body>
</html>
通过js构造出来的"select"代码如:
通过js构造出来的html
<div class="searchBar">
<div class="select">
<input type="text" id="c_input" class="selectbox" autocomplete="off" readonly="" tabindex="0">
<div id="c_container" class="selectbox-wrapper" style="display:none">
<ul>
<li id="c_input_1" class="selected">生活信息</li>
<li id="c_input_2" class="">店铺商家</li>
<li id="c_input_3" class="">新闻资讯</li>
<li id="c_input_4" class="">团购活动</li>
<li id="c_input_5" class="">招聘信息</li>
</ul>
</div>
<select name="c" style="display:none" id="c">
<option value="1">生活信息</option>
<option value="2">店铺商家</option>
<option value="3">新闻资讯</option>
<option value="4">团购活动</option>
<option value="5">招聘信息</option>
</select>
</div>
<div class="text">
<input name="keyword" value="shuidd.com" onfocus="if(this.value=='shuidd.com'){this.value='';this.style.color='#000000'}" onblur="if(this.value==''){this.value='shuidd.com';this.style.color='#aaa'}" class="s_t" style="color: rgb(170, 170, 170);">
</div>
<a class="btn" href="#"><img alt="" src="images/btn.gif"></a>
</div>
<div class="select">
<input type="text" id="c_input" class="selectbox" autocomplete="off" readonly="" tabindex="0">
<div id="c_container" class="selectbox-wrapper" style="display:none">
<ul>
<li id="c_input_1" class="selected">生活信息</li>
<li id="c_input_2" class="">店铺商家</li>
<li id="c_input_3" class="">新闻资讯</li>
<li id="c_input_4" class="">团购活动</li>
<li id="c_input_5" class="">招聘信息</li>
</ul>
</div>
<select name="c" style="display:none" id="c">
<option value="1">生活信息</option>
<option value="2">店铺商家</option>
<option value="3">新闻资讯</option>
<option value="4">团购活动</option>
<option value="5">招聘信息</option>
</select>
</div>
<div class="text">
<input name="keyword" value="shuidd.com" onfocus="if(this.value=='shuidd.com'){this.value='';this.style.color='#000000'}" onblur="if(this.value==''){this.value='shuidd.com';this.style.color='#aaa'}" class="s_t" style="color: rgb(170, 170, 170);">
</div>
<a class="btn" href="#"><img alt="" src="images/btn.gif"></a>
</div>
然后js将原始select中的项全部复制到一个ul的li中,并附上css样式来实现美化 ul li,来实现美化构造出的"select”,js代码如下:
beautifySelect.js
/*!
* Date: 2011-3-29
* Author: musical_insect
* Content: beautify select box by jQuery and css
*/
jQuery.fn.extend({
beautifyselect: function (options) {
returnthis.each(function () {
new jQuery.BeautifySelect(this, options);
});
}
});
/* pawel maziarz: work around for ie logging */
if (!window.console) {
var console = {
log: function (msg) {}
}
};
jQuery.BeautifySelect =function (selectobj, options) {
/// <summary>
/// beautify select
/// </summary>
/// <param name="selectobj" type="Dom">select object</param>
/// <param name="options" type="object">options,format:{inputClass:selectbox,containerClass:selectbox-wrapper,hoverClass:hover,selectedClass:selected}</param>
var opt = options || {};
opt.inputClass = opt.inputClass ||"selectbox";
opt.containerClass = opt.containerClass ||"selectbox-wrapper";
opt.hoverClass = opt.hoverClass ||"hover";
opt.currentClass = opt.selectedClass ||"selected";
opt.debug = opt.debug ||false;
var elm_id = selectobj.id;
var active =0;
var hasfocus =0;
//jquery object for select element
var $select = $(selectobj);
// jquery container object
var $container = setupContainer(opt);
//jquery input object
var $input = setupInput(opt);
// hide select and append newly created elements
$select.hide().before($input).before($container);
init();
$input.click(function (event) {
$container.toggle();
}).keydown(function (event) {
switch (event.which) {
case38: // up
event.preventDefault();
moveSelect(-1);
break;
case40: // down
event.preventDefault();
moveSelect(1);
break;
//case 9: // tab
case13: // enter
event.preventDefault(); // seems not working in mac !
$('li.'+ opt.hoverClass).trigger('click');
break;
case27: //escape
hideMe();
break;
}
}).blur(function () {
if ($container.is(':visible') && hasfocus >0) {
if (opt.debug) console.log('container visible and has focus')
} else {
try {
// Workaround for ie scroll - thanks to Bernd Matzner
if ($.browser.msie || $.browser.safari) { // check for safari too - workaround for webkit
if (document.activeElement.getAttribute('id').indexOf('_container') ==-1) {
hideMe();
} else {
$input.focus();
}
} else {
hideMe();
}
} catch (Error) { hideMe(); }
}
});
//隐藏下拉菜单容器
function hideMe() {
hasfocus =0;
$container.hide();
}
//初始化下拉菜单
function init() {
$container.append(getSelectOptions($input.attr('id'))).hide();
}
//初始化下拉菜单容器并进行相关设置
function setupContainer(options) {
var container = document.createElement("div");
$container = $(container);
$container.attr('id', elm_id +'_container');
$container.addClass(options.containerClass);
return $container;
}
//初始化下拉菜单并进行相关设置
function setupInput(options) {
var input = document.createElement("input");
var $input = $(input);
$input.attr("id", elm_id +"_input");
$input.attr("type", "text");
$input.addClass(options.inputClass);
$input.attr("autocomplete", "off");
$input.attr("readonly", "readonly");
$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
return $input;
}
//处理下拉菜单响应键盘上的上、下键
function moveSelect(step) {
var lis = $("li", $container);
if (!lis || lis.length ==0) returnfalse;
active += step;
//loop through list
if (active <0) {
active = lis.size() -1;
} elseif (active > lis.size() -1) {
active =0;
}
scroll(lis, active);
lis.removeClass(opt.hoverClass);
$(lis[active]).addClass(opt.hoverClass);
$input.val($(lis[active]).html());
}
function scroll(list, active) {
var el = $(list[active]).get(0);
var list = $container.get(0);
if (el.offsetTop + el.offsetHeight > list.scrollTop + list.clientHeight) {
list.scrollTop = el.offsetTop + el.offsetHeight - list.clientHeight;
} elseif (el.offsetTop < list.scrollTop) {
list.scrollTop = el.offsetTop;
}
}
//处理当前选择中的值
function setCurrent() {
var li = $("li."+ opt.currentClass, $container).get(0);
var ar = (''+ li.id).split('_');
var el = ar[ar.length -1];
$select.val(el);
$input.val($(li).html());
returntrue;
}
//获取当前选中项的索引
function getCurrentSelected() {
return $select.val();
}
//获取当前选中项的值
function getCurrentValue() {
return $input.val();
}
//获取下拉菜单的选择项
function getSelectOptions(parentid) {
var select_options =new Array();
var ul = document.createElement('ul');
$select.children('option').each(function () {
var li = document.createElement('li');
li.setAttribute('id', parentid +'_'+ $(this).val());
li.innerHTML = $(this).html();
if ($(this).is(':selected')) {
$input.val($(this).html());
$(li).addClass(opt.currentClass);
}
ul.appendChild(li);
$(li).mouseover(function (event) {
hasfocus =1;
if (opt.debug) console.log('over on : '+this.id);
jQuery(event.target, $container).addClass(opt.hoverClass);
}).mouseout(function (event) {
hasfocus =-1;
if (opt.debug) console.log('out on : '+this.id);
jQuery(event.target, $container).removeClass(opt.hoverClass);
}).click(function (event) {
var fl = $('li.'+ opt.hoverClass, $container).get(0);
if (opt.debug) console.log('click on :'+this.id);
$('#'+ elm_id +'_container'+' li.'+ opt.currentClass).removeClass(opt.currentClass);
$(this).addClass(opt.currentClass);
setCurrent();
//$select.change();
$select.get(0).blur();
hideMe();
});
});
return ul;
}
};
* Date: 2011-3-29
* Author: musical_insect
* Content: beautify select box by jQuery and css
*/
jQuery.fn.extend({
beautifyselect: function (options) {
returnthis.each(function () {
new jQuery.BeautifySelect(this, options);
});
}
});
/* pawel maziarz: work around for ie logging */
if (!window.console) {
var console = {
log: function (msg) {}
}
};
jQuery.BeautifySelect =function (selectobj, options) {
/// <summary>
/// beautify select
/// </summary>
/// <param name="selectobj" type="Dom">select object</param>
/// <param name="options" type="object">options,format:{inputClass:selectbox,containerClass:selectbox-wrapper,hoverClass:hover,selectedClass:selected}</param>
var opt = options || {};
opt.inputClass = opt.inputClass ||"selectbox";
opt.containerClass = opt.containerClass ||"selectbox-wrapper";
opt.hoverClass = opt.hoverClass ||"hover";
opt.currentClass = opt.selectedClass ||"selected";
opt.debug = opt.debug ||false;
var elm_id = selectobj.id;
var active =0;
var hasfocus =0;
//jquery object for select element
var $select = $(selectobj);
// jquery container object
var $container = setupContainer(opt);
//jquery input object
var $input = setupInput(opt);
// hide select and append newly created elements
$select.hide().before($input).before($container);
init();
$input.click(function (event) {
$container.toggle();
}).keydown(function (event) {
switch (event.which) {
case38: // up
event.preventDefault();
moveSelect(-1);
break;
case40: // down
event.preventDefault();
moveSelect(1);
break;
//case 9: // tab
case13: // enter
event.preventDefault(); // seems not working in mac !
$('li.'+ opt.hoverClass).trigger('click');
break;
case27: //escape
hideMe();
break;
}
}).blur(function () {
if ($container.is(':visible') && hasfocus >0) {
if (opt.debug) console.log('container visible and has focus')
} else {
try {
// Workaround for ie scroll - thanks to Bernd Matzner
if ($.browser.msie || $.browser.safari) { // check for safari too - workaround for webkit
if (document.activeElement.getAttribute('id').indexOf('_container') ==-1) {
hideMe();
} else {
$input.focus();
}
} else {
hideMe();
}
} catch (Error) { hideMe(); }
}
});
//隐藏下拉菜单容器
function hideMe() {
hasfocus =0;
$container.hide();
}
//初始化下拉菜单
function init() {
$container.append(getSelectOptions($input.attr('id'))).hide();
}
//初始化下拉菜单容器并进行相关设置
function setupContainer(options) {
var container = document.createElement("div");
$container = $(container);
$container.attr('id', elm_id +'_container');
$container.addClass(options.containerClass);
return $container;
}
//初始化下拉菜单并进行相关设置
function setupInput(options) {
var input = document.createElement("input");
var $input = $(input);
$input.attr("id", elm_id +"_input");
$input.attr("type", "text");
$input.addClass(options.inputClass);
$input.attr("autocomplete", "off");
$input.attr("readonly", "readonly");
$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
return $input;
}
//处理下拉菜单响应键盘上的上、下键
function moveSelect(step) {
var lis = $("li", $container);
if (!lis || lis.length ==0) returnfalse;
active += step;
//loop through list
if (active <0) {
active = lis.size() -1;
} elseif (active > lis.size() -1) {
active =0;
}
scroll(lis, active);
lis.removeClass(opt.hoverClass);
$(lis[active]).addClass(opt.hoverClass);
$input.val($(lis[active]).html());
}
function scroll(list, active) {
var el = $(list[active]).get(0);
var list = $container.get(0);
if (el.offsetTop + el.offsetHeight > list.scrollTop + list.clientHeight) {
list.scrollTop = el.offsetTop + el.offsetHeight - list.clientHeight;
} elseif (el.offsetTop < list.scrollTop) {
list.scrollTop = el.offsetTop;
}
}
//处理当前选择中的值
function setCurrent() {
var li = $("li."+ opt.currentClass, $container).get(0);
var ar = (''+ li.id).split('_');
var el = ar[ar.length -1];
$select.val(el);
$input.val($(li).html());
returntrue;
}
//获取当前选中项的索引
function getCurrentSelected() {
return $select.val();
}
//获取当前选中项的值
function getCurrentValue() {
return $input.val();
}
//获取下拉菜单的选择项
function getSelectOptions(parentid) {
var select_options =new Array();
var ul = document.createElement('ul');
$select.children('option').each(function () {
var li = document.createElement('li');
li.setAttribute('id', parentid +'_'+ $(this).val());
li.innerHTML = $(this).html();
if ($(this).is(':selected')) {
$input.val($(this).html());
$(li).addClass(opt.currentClass);
}
ul.appendChild(li);
$(li).mouseover(function (event) {
hasfocus =1;
if (opt.debug) console.log('over on : '+this.id);
jQuery(event.target, $container).addClass(opt.hoverClass);
}).mouseout(function (event) {
hasfocus =-1;
if (opt.debug) console.log('out on : '+this.id);
jQuery(event.target, $container).removeClass(opt.hoverClass);
}).click(function (event) {
var fl = $('li.'+ opt.hoverClass, $container).get(0);
if (opt.debug) console.log('click on :'+this.id);
$('#'+ elm_id +'_container'+' li.'+ opt.currentClass).removeClass(opt.currentClass);
$(this).addClass(opt.currentClass);
setCurrent();
//$select.change();
$select.get(0).blur();
hideMe();
});
});
return ul;
}
};