我如何将 div
作为单选框使用?
我的意思是:
- 你可以选择一个
div
,然后它会被加上蓝色的边框 - 你只能选择其中一个
如果您想要一个纯CSS的解决方案,这是一个非常好的选择:
.labl {
display : block;
width: 400px;
}
.labl > input{ /* HIDE RADIO */
visibility: hidden; /* Makes input not-clickable */
position: absolute; /* Remove input from document flow */
}
.labl > input + div{ /* DIV STYLES */
cursor:pointer;
border:2px solid transparent;
}
.labl > input:checked + div{ /* (RADIO CHECKED) DIV STYLES */
background-color: #ffd6bb;
border: 1px solid #ff6600;
}
<label class="labl">
<input type="radio" name="radioname" value="one_value" checked="checked"/>
<div>Small</div>
</label>
<label class="labl">
<input type="radio" name="radioname" value="another" />
<div>Small</div>
</label>
受这个答案的启发
是的,您可以使用“div”作为单选按钮,并将其作为单选按钮组工作。但是,为此,您需要使用JavaScript。我已经使用JQuery创建了一个脚本。这是源码--
$('.radio-group .radio').click(function(){
$(this).parent().find('.radio').removeClass('selected');
$(this).addClass('selected');
var val = $(this).attr('data-value');
//alert(val);
$(this).parent().find('input').val(val);
});
.radio-group{
position: relative;
}
.radio{
display:inline-block;
width:15px;
height: 15px;
border-radius: 100%;
background-color:lightblue;
border: 2px solid lightblue;
cursor:pointer;
margin: 2px 0;
}
.radio.selected{
border-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select an option (You will get it's value displayed in the text input field!)</h2>
<form method="post" action="send.php">
<div class="radio-group">
<div class='radio' data-value="One"></div>1
<div class='radio' data-value="Two"></div>2
<div class='radio' data-value="Three"></div>3
<br/>
<input type="text" id="radio-value" name="radio-value" />
</div>
</form>
<div class="option first">1</div>
<div class="option second">2</div>
<div class="option third">3</div>
<div class="option fourth">4</div>
CSS
.option
{
background-color:red;
margin: 10px auto;
}
.option.active
{
border:1px solid blue;
}
Jquery
$(document).ready(
function()
{
$(".option").click(
function(event)
{
$(this).addClass("active").siblings().removeClass("active");
}
);
});
看看这个。严格的HTML/CSS解决方案(标签内没有div):
input {display: none;}
label {display: block;}
input + div {
background: orange;
}
input + div label {
padding: 10px;
cursor: pointer;
}
input:checked + div {
background: red;
}
<input type="radio" id="one" name="test" value="ONE">
<div><label for="one">ONE</label></div>
<input type="radio" id="two" name="test" value="TWO">
<div><label for="two">TWO</label></div>
<input type="radio" id="three" name="test" value="THREE">
<div><label for="three">THREE</label></div>
这种方法使用 div 中的标签(而不是标签中的 div,这是非法的)。您可以在 div 中放置任何其他元素。
如果您希望整个 div 作为单选按钮可点击,则其标签必须覆盖其完整的宽度和高度。所有情况的最简单解决方案是 label {position: absolute; width: 100%; height: 100%;}
以及 input + div {position: relative;}
。并将标签放在 div 中的任何其他元素之后。