web页面中点击button按钮变色,再次点击变回来
问题描述:
1.页面中有多个button,需要实现点击一个单独变色,再次点击变回原来的颜色,其它按钮都是单独控制
这个js只能实现一个按钮变色,改变class或者id都不能实现我想要的,哪位大哥帮我一下,刚接触前端~
答
<button onclick="change(this)">登录1</button>
<button onclick="change(this)">登录2</button>
<script>
function change(i){
if(i.style.backgroundColor ==""){
i.style.backgroundColor="red";
}
else{
i.style.backgroundColor="";
}
}
</script>
答
是要点击后针对某一个按钮变色吗?
这段代码值对 button1 添加了点击事件,点击基数次是下面的颜色,偶数是另一个颜色。
答
<template>
<div class="about">
<div v-for="(item,i) in list" class="btn" :class="item.status?'active':''" @click="changeBtn(i)">{{i}}</div>
</div>
</template>
<script lang="ts">
import {Component, Vue} from 'vue-property-decorator';
@Component
export default class ButtonChange extends Vue {
private list:any = [{
name: '1',
status: false,
},{
name: '2',
status: false,
},{
name: '3',
status: false,
},{
name: '4',
status: false,
},{
name: '5',
status: false,
},{
name: '6',
status: false,
}];
private changeBtn ( i :number ) {
this.list[i].status = !this.list[i].status;
}
}
</script>
<style scoped lang="scss">
.btn {
cursor: pointer;
width: 50px;
height: 20px;
line-height: 20px;
border-radius: 4px;
background: #ccc;
margin: 0 8px 8px;
float: left;
}
.btn.active{
background: #42b983;
}
</style>
参考一下,这是你想要的结果吗?
就是用双向绑定改变item的状态,切换class。
答
你这个太复杂了吧,直接onclick里面的方法传this,获取到当前按钮,然后修改他的style就可以了
答
我记得有个动态绑定的