<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
font-family: "微软雅黑";
font-size: 15px;
}
ul{
list-style: none;
}
input{
outline: 0;
}
.content{
margin:100px
}
.choose-problem {
border: 1px solid #D3D3D3;
cursor: pointer;
height: 34px;
line-height: 34px;
width: 200px;
text-indent: 10px;
position: relative;
margin-right: 10px;
display: block;
}
.down {
background: url(img/down.png);
width: 10px;
height: 10px;
position: absolute;
right: 10px;
top: 15px;
}
.choose-problem .choose-value {
width: 100%;
height: 34px;
display: block;
}
.choose-value.active {
outline: 1px solid #187AFF;
}
.choose-problem .choose-list {
position: absolute;
top: 37px;
width: 100%;
display: none;
z-index: 2;
background: #fff;
border: 1px solid #d3d3d3;
}
.choose-problem .choose-list .choose-item {
width: 100%;
height: 30px;
line-height: 30px;
}
.choose-problem .choose-list .choose-item:hover{
background-color: #EFEFEF;
}
.btn{
display: inline-block;
border-radius: 5px;
background:#187AFF;
color:#fff;
height: 30px;
padding:5px;
border:0;
margin-top:40px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="content">
<span class="choose-problem">
<span class="down"></span>
<span class="choose-value" data-index="1">我的梦想是?</span>
<ul class="choose-list">
<li class="choose-item" data-index="1">我的梦想是?</li>
<li class="choose-item" data-index="2">对我最有影响的人是?</li>
<li class="choose-item" data-index="3">我最喜欢的美食是?</li>
<li class="choose-item" data-index="4">我最喜欢的地方是?</li>
<li class="choose-item" data-index="5">我最喜欢的节日是?</li>
<li class="choose-item" data-index="6">我最重要的纪念日是?</li>
<li class="choose-item" data-index="7">我的偶像是?</li>
<li class="choose-item" data-index="8">自定义问题</li>
</ul>
</span>
<span><input type="button" value="获取Select的值" onclick="getValue()" class="btn"/></span>
</div>
<script src="js/jquery-1.10.1.min.js"></script>
<script>
$(function() {
// 下拉显示隐藏
$('.choose-value').click(function() {
if ($(this).hasClass("active")) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
$(this).parent().find('.choose-list').toggle();
});
// 选择选项后赋值
$('.choose-item').click(function() {
var _detail = $(this).text();
var _value = $(this).attr("data-index");
$(this).parent().parent().find(".choose-value").text(_detail);
$(this).parent().parent().find(".choose-value").attr("data-index", _value);
$(this).parent().hide();
$('.choose-value').removeClass('active');
});
//点击其他区域隐藏下拉选项
$(document).bind("click",function(e){
var target = $(e.target);
if(target.closest(".choose-problem").length == 0){
$(".choose-list").hide();
$(".choose-value").removeClass("active");
}
});
});
function getValue(){
//使用html自定义的“data-”属性
var text = $(".choose-value").text();
var value = $(".choose-value").attr("data-index");
alert("值为:"+value+"; 文本为:"+text);
}
</script>
</body>
</html>