我在容器中放置了一个图像和 3 个单选按钮。当某些单选按钮被选中时,我想添加另一个图像出现在容器主图像上。每个按钮在激活时都会有不同的图像显示位置。
到目前为止我明白了:
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" id="q156" name="quality[25]" value="1" /> 1
</label>
<label class="btn btn-default">
<input type="radio" id="q157" name="quality[25]" value="2" /> 2
</label>
<label class="btn btn-default">
<input type="radio" id="q158" name="quality[25]" value="3" /> 3
</label>
</div>
</div>
</div>
<div class="col-md-8 col-fl">
<div id="img_box">
<img style="width: 100%;" src="img/other/rounded_corners.png" />
</div>
最佳答案
您可以将图像源添加为数据属性。到单选按钮。
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" id="q156" name="quality[25]" value="1" data-img="http://placehold.it/350x150/ff0000" /> 1
</label>
<label class="btn btn-default">
<input type="radio" id="q157" name="quality[25]" value="2" data-img="http://placehold.it/350x150/00ff00"/> 2
</label>
<label class="btn btn-default">
<input type="radio" id="q158" name="quality[25]" value="3" data-img="http://placehold.it/350x150/0000ff" /> 3
</label>
</div>
<div class="col-md-8 col-fl">
<div id="img_box"></div>
img 框是空的,但大小和图像由 css 设置:
#img_box{
width: 350px;
height: 150px;
background: url('http://placehold.it/350x150/ff0000')
}
然后添加一个事件,在点击时附加一个 img 叠加层(使用来自单选按钮的来源):
$(function(){
$('input[type=radio]').click(function(){
$this = $(this)
$img_box = $('#img_box')
$overlay = $('<img/>').attr('src',$this.data('img'))
$img_box.html('').append($overlay)
});
})
关于javascript - 如何通过单选按钮更改元素(img)的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31721098/