我需要一个类似按钮的控件,该控件具有选中的属性,以便单击时它保持按下状态。类似于下面示例图中的“清除响应”按钮。
我怎样才能在 CSS 中做到这一点?我是 CSS 新手。有人可以提供一个例子或指出与此类似的例子吗?
PS:我知道我需要使用Javascript来更新保存按钮状态的布尔变量,并动态地将样式应用到按钮。我的问题更像是如何创建一个包含复选框的按钮,因为我只有一张背景图像。
至于CSS,你可以执行以下操作:
<style type='text/css'>
/* this is the style of an unchecked "button" */
.input-check{
display:inline-block;
height:20px;
padding:5px 8px;
background:green;
width:70px;
color:white
}
/* This is the style for a checked "button" */
.input-check.checked{
background:red;
color:black;
font-weight:bold
}
/* Hide the checkbox */
.input-check input{
display:none
}
</style>
Run Code Online (Sandbox Code Playgroud)
接下来是 HTML。为了减少 JavaScript 编码,最好将复选框嵌套在标签内。这将使其在您单击标签时自动处理复选框的选中/取消选中。
<label class="input-check"><input onchange="change_state(this)" type="checkbox" value="something" name="test"/> click me </label>
Run Code Online (Sandbox Code Playgroud)
最后是 JavaScript:
<script type="text/javascript">
/* If you have more experience in JavaScript, I recommend not binding the change event this way, I didn't bother much about this part, since I guess it isn't part of the question */
function change_state(obj){
if (obj.checked){
//if checkbox is being checked, add a "checked" class
obj.parentNode.classList.add("checked");
}
else{
//else remove it
obj.parentNode.classList.remove("checked");
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
这是一个供您测试的jsFiddle 。
| 归档时间: |
|
| 查看次数: |
8254 次 |
| 最近记录: |