编辑:
感谢Brad Christie提供代码
我切换到使用复选框。
页面上有 8 个复选框,我希望最多允许 4 个可互换的选择。
选中复选框时,我希望在 div 元素下方显示图像,并在图像底部滑入虚线。
$(文档).ready(函数 () {
var $ids = $('#weird,#crazy,#cool,#foul,#great,#amazing,#good,#decent'), $boxes = $('#box1,#box2,#box3,#box4 ');
function addSelection(id) {
var $empty = $boxes.filter('[src=""]');
if ($empty.size() > 0) {
// empty spot available, fill it with the ID
$empty.first().attr('src', id+'.png');
return true;
}
return false;
}
function removeSelection(id) {
var $match = $boxes.filter('[src$="'+id+'"]');
if ($match.size() > 0) {
// found a match for this ID, so remove it.
$match.attr('src', '');
return true;
}
// didn't find a match for this id
return false;
}
$ids.on('click', function(e){
var $this = $(this);
if (removeSelection(this.id)) {
$this.removeClass('selected');
} else if (addSelection(this.id)) {
$this.addClass('selected');
}
e.preventDefault();
});
});
标记:
<form>
<div id="weird"><div class="v"><input type="checkbox" name="what_did" value="smart_thrift">Smart Thrift</div></div>
<div id="crazy"><div class="v"><input type="checkbox" name="what_did" value="foodie">Foodie</div></div>
<div id="cool"><div class="v"><input type="checkbox" name="what_did" value="outdoors">Outdoors</div></div>
<div id="foul"><div class="v"><input type="checkbox" name="what_did" value="fashion">Fashion</div></div>
<div id="great"><div class="v"><input type="checkbox" name="what_did" value="culture">Culture</div></div>
<div id="amazing"><div class="v"><input type="checkbox" name="what_did" value="fitness">Fitness</div></div>
<div id="good"><div class="v"><input type="checkbox" name="what_did" value="kids_friendly">Kids Friendly</div></div>
<div id="decent"><div class="v"><input type="checkbox" name="what_did" value="home_improv">Home Improvement</div></div>
</form>
<div>
<img id="box1" src="" />
<img id="box2" src="" />
<img id="box3" src="" />
<img id="box4" src="" />
</div>
<div id="line1"></div>
<div id="line2"></div>
<div id="line3"></div>
<div id="line4"></div>
<div id="line5"></div>