原理是用span
标签作为显示,input
隐藏在span
标签后,
获取点击事件。
基于vue2.0进行编写,未使用框架,仅引入了vue.js。
效果如图:
<!DOCTYPE html>
<html>
<head>
</head>
<style>
body{
background-color: cadetblue;
}
.line{
display: flex;
justify-content: space-between;
align-items: center;
}
.radio-box{
display: inline-block;
position: relative;
height: 25px;
line-height: 25px;
margin-right: 5px;
flex-basis: 50%;
display: flex;
align-items: center;
}
.radio:before{
content: '';
}
.radio {
display: inline-block;
width: 15px;
height: 15px;
border-radius: 50%;
border: 2px solid #ffffff;
margin-right: 0.25rem;
}
.input-radio {
display: inline-block;
position: absolute;
opacity: 0;
width: 100%;
height: 100%;
cursor: pointer;
left: 0px;
outline: none;
-webkit-appearance: none;
}
.on::after {
content: '';
width: 11px;
height: 11px;
background: #f2b449;
position: absolute;
border-radius: 50%;
top: 7px;
left: 4px;
}
.btn{
height: 2.2rem;
width: 5.5rem;
margin: 2rem auto;
background-color: bisque;
border-radius: 2rem;
line-height: 2.2rem;
text-align: center;
}
</style>
<div id="app">
<div class="" v-for="(question,quesIndex) in radioList">
<div class="line">
<p>{{question.Title}}</p>
</div>
<div class="line">
<div v-for="(item,index) in question.Options" class="radio-box" :key="item.value">
<span class="radio" :class="{'on':item.isChecked}"></span>
<input :value="item.value" class="input-radio" v-on:click="check(index,quesIndex)" type="radio">
<span>{{item.label}}</span>
</div>
</div>
</div>
<div class="btn" v-on:click="onSubmit">
提交
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="module">
new Vue({
el:'#app',
data:()=>{
return {
submitForm: {},
radioList:[
{
"Title": "题目1",
"Options": [
{
"label": "可以",
"value": "可以",
"isChecked": true
},
{
"label": "不可以",
"value": "不可以",
"isChecked": false
}
]
},
{
"Title": "题目2",
"Options": [
{
"label": "男",
"value": "男",
"isChecked": true
},
{
"label": "女",
"value": "女",
"isChecked": false
}
]
}
]
}
},
created() {
this.initSubmitForm()
},
methods: {
initSubmitForm(){
this.radioList.forEach((item,index)=>{
let checkedOpt = item.Options.find(option=>option.isChecked == true)
this.submitForm[index] = checkedOpt ? checkedOpt.value : ""
})
console.log(this.submitForm)
},
check(index,quesIndex) {
// 先取消所有选中项
this.radioList[quesIndex].Options.forEach(item => {
item.isChecked = false;
});
console.log(this.radioList)
//再设置当前点击项选中
this.radioList[quesIndex].Options[index].isChecked = true;
this.submitForm[quesIndex] = this.radioList[quesIndex].Options[index].value;
console.log(this.submitForm)
},
onSubmit(){
let tempList = Object.values(this.submitForm)
console.log(tempList)
console.log(this.submitForm);
}
}
})
</script>
</html>