我想做的是:好吧,我想在这里构建一个样式转换器,它是如何工作的。
我需要帮助检查条件:如果变量在数组中,请转到"Div"删除数组中的所有类。
结构:
//无线电组1(彩色)
<input type="radio" name="color" id="red" >
<input type="radio" name="color" id="blue" checked>
<input type="radio" name="color" id="green">
以阵列颜色动态存储每个无线电组(所有阵列名称与无线电组名称相同)
var color = ['red','blue','green'];
//无线电组2(尺寸)
<input type="radio" name="size" id="fluid" checked>
<input type="radio" name="size" id="boxed">
动态存储来自输入值的大小数组
var size = ['fluid','boxed'];
示例html:
<div class" blue fluid">
. . .
</div>
获取用户输入
var isChecked = $('#form').on('change',function(){
isChecked = $(this).attr('id');
}
这是我现在卡住的每个单选按钮的if条件。。
//如果用户选择红色
//---------------------
if( isChecked == 'red'){
// remove any class(blue) from "Div" that match the value in array color[].
// keep classes(fluid) as is if it's not in array color[].
//---------------------------
// add new class or ID to the DIV.
}
//如果用户选择红色
//---------------------
if( isChecked == 'red'){
// remove any class(blue) from "Div" that match the value in array color[].
// keep classes(fluid) as is if it's not in array color[].
//---------------------------
// add new class or ID to the DIV.
}
//如果用户选择蓝色
//---------------------
if( isChecked == 'blue'){
// remove any class(blue) from "Div" that match the value in array color[].
// keep classes(fluid) as is if it's not in array color[].
//---------------------------
// add new class or ID to the DIV.
}
//如果用户选择绿色
//---------------------
if( isChecked == 'green'){
// remove any class(blue) from "Div" that match the value in array color[].
// keep classes(fluid) as is if it's not in array color[].
//---------------------------
// add new class or ID to the DIV.
}
不要专门删除div
元素上设置的类,而是使用removeClass()
将它们全部删除,并根据选中的选项重新应用它们,类似于以下内容:
$('input[name="color"], input[name="size"]').change(function() {
var $div = $('#foo').removeClass('red blue green fluid boxed');
var color = $('input[name="color"]:checked').val();
var size = $('input[name="size"]:checked').val();
$div.addClass(color + ' ' + size);
});
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
.fluid {
width: 50px;
height: 50px;
}
.boxed {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="color" value="red"> Red
<input type="radio" name="color" value="blue" checked> Blue
<input type="radio" name="color" value="green"> Green
<br />
<input type="radio" name="size" value="fluid" checked> Fluid
<input type="radio" name="size" value="boxed"> Boxed
<div id="foo" class="blue fluid"></div>