您的位置:首页 > 编程语言

使用div模拟默认select效果代码。

2018-02-18 23:45 375 查看
我们在开发过程中很多时候都发现系统默认的select可能有点丑,或者有时候并不能满足UI设计的样式要求,于是就得自己写一个模拟出效果,并可以向服务端传送数据。大年初三敲代码,只是闲来敲敲。。。。。。

效果如下:



代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/cs.css" disabled="true">
<style>
body{padding:30px;font-family: "微软雅黑";}
li{list-style: none;}
*{padding:0;margin:0;}
#selector{position:relative;height:30px;width:210px;font-size:13px;line-height:30px;text-align:left;user-select:none;}
#selector select{display:none;}
#selector .arrow{position:absolute;right:5px;top:12px;display:block;height:0;width:0;border-top:8px solid red;border-right:5px solid transparent;border-left:5px solid transparent;}
#selector .mr-selector{display:block;height:30px;width:200px;padding-left:10px;border:1px solid red;cursor:default;}
#selector .select{display:none;width:210px;margin-top:-1px;border:1px solid red;}
#selector .select li{height:30px;line-height:30px;padding-left:10px;}
#selector .select li:hover{background:red;color:#fff;cursor:default;}
</style>
<title>selector插件</title>
</head>
<body>
<div id="selector">
<select class="hd-selector">
<option value="0" selected="selected">默认选项</option>
<option value="1">选项内容一</option>
<option value="2">选项内容二</option>
<option value="3">选项内容三</option>
<option value="4">选项内容四</option>
</select>
<span class="mr-selector">请选择选项</span>
<span class="arrow"></span>
<ul class="select">
<li>请选择选项</li>
<li>选项内容一</li>
<li>选项内容二</li>
<li>选项内容三</li>
<li>选项内容四</li>
</ul>
</div>
<script src="../Util/jquery-1.11.3.min.js"></script>
<script>
(function(){

var selector = $("#selector");
var select = $("#selector .select");  //模拟select的ul选项
var mrSelector = $("#selector .mr-selector");
var li = $("#selector .select li"); //li选项

selector.click(function(eve){
eve.stopPropagation();   //阻止冒泡避免点击后消失
});

mrSelector.click(function(){
select.toggle();
});

li.click(function(eve){
var index = $(this).index();
console.log(index);
var text = $(this).text();  //获取当前点击li文本
mrSelector.text(text);      //赋值默认选项文本
console.log($("#selector .hd-selector option"));
selector.find(".hd-selector option").eq(index)
.attr("selected","selected").siblings().removeAttr("selected");
$(this).parent().hide();

});

$("body").click(function(){
select.hide();
});

}());

</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: