我正在製作一個ul li
元素函數,如select
輸入,用戶可以從中爲該框選擇顏色。重新排列jQuery中的列表元素
下面的代碼:
$(document).ready(function() {
$('.color-picker ul.color-list li.active .text').after('<span class="pull-right glyphicon glyphicon-menu-down"></span>');
$('.color-picker ul.color-list li').click(function() {
if ($(this).hasClass('active')) {
console.log(2);
$('.color-picker ul.color-list li').show();
} else {
console.log(1);
var color = $(this).find('.box').css('backgroundColor');
$('.color-picker .color-box').css({
'background-color': color
});
$('.color-picker ul.color-list li.active').removeClass('active');
$('.color-picker ul.color-list li').hide();
$(this).addClass('active');
$('.color-picker ul.color-list li.active').show();
$('.color-picker ul.color-list li .glyphicon').remove();
$('.color-picker ul.color-list li.active .text').after('<span class="pull-right glyphicon glyphicon-menu-down"></span>');
}
});
});
.color-picker {
display: flex;
margin: 20px;
border: 1px solid #d9d9d9;
padding: 10px;
width: 350px;
}
.color-picker .color-box {
display: inline-block;
background-color: black;
height: 50px;
width: 50px;
}
.color-picker ul.color-list {
display: inline-block;
margin: 0;
position: absolute;
}
.color-picker ul.color-list li {
list-style: none;
border: 1px solid #d9d9d9;
padding: 10px;
cursor: pointer;
width: 200px;
background-color: white;
}
.color-picker ul.color-list li.active {
display: block;
}
.color-picker ul.color-list li {
display: none;
}
.color-picker ul.color-list li .box {
content: "";
display: inline-block;
height: 10px;
width: 30px;
margin-right: 10px;
}
.color-picker ul.color-list li.red .box {
background-color: #c71212;
}
.color-picker ul.color-list li.blue .box {
background-color: #0d89d1;
}
.color-picker ul.color-list li.green .box {
background-color: #18c771;
}
.color-picker .as-select .select-default {
border: 1px solid #d9d9d9;
padding: 10px 20px;
width: 200px;
margin-left: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-picker">
<div class="color-box">
</div>
<div class="as-select">
<ul class="color-list">
<li class="red active">
<span class="box"></span>
<span class="text">Red</span>
</li>
<li class="blue">
<span class="box"></span>
<span class="text">Blue</span>
</li>
<li class="green">
<span class="box"></span>
<span class="text">Green</span>
</li>
</ul>
</div>
</div>
正如你所看到的有源元件保持在同一個地方。
(選擇藍色,然後再次單擊下拉)
是他們的一種方法,我可以使所選元素列表中的第一個孩子?
使用柔性盒定位並設置o首先選擇元素(請參見[這裏](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)以獲取有關使用柔性定位的更多信息)。當然,這取決於你瞄準哪些瀏覽器,但根據[caniuse](http://caniuse.com/#feat=flexbox),對flex的支持現在相當不錯,> 96%。 –