表格鼠标悬浮修改行的背景色,单击行也要有背景色

需求背景:需要对表格同时实现鼠标悬浮行有背景色,单击行时也要有背景色。

主要注意点:

  1. 给表格行添加 悬浮背景色:tr:hover
  2. 在给选中行添加背景色时,让其背景色为 !important,这样鼠标悬浮时就不会覆盖选中行的背景色。

解决方案:

CSS:

.select{
  background-color:cadetblue !important;
}
table tr:hover{
   background-color: brown;
}

 

HTML:

        <table cellpadding="0" cellspacing="0" >
            <tr>
                <td>id</td>
                <td>水果名</td>
                <td>创建时间</td>
                <td>操作</td>
            </tr>
            <tr :id="'tr'+item.id" v-for="item in search(keywords)" :key="item.id" @click="select(item.id)">
                <td>{{item.id}}</td>
                <td v-text="item.name"></td>
                <td>{{item.ctime}}</td>
                <td><input type="button" value="删除"></td>
            </tr>
        </table>

JS:

var vm = new Vue({
        el: '#app',
        data: {
            id: '',
            name: '',
            keywords: '',
            fruitArr: [
                { id: 1, name: '苹果', ctime: new Date() },
                { id: 2, name: '李子', ctime: new Date() }
            ]
        },
        methods: {
            select(id){
                console.log(id);
                var dom = document.getElementById("tr"+id);
                this.clearStyle(); // 清除原来被选中元素的样式
                dom.classList.add('select')
            },
            clearStyle(){
                var doms = document.getElementsByClassName("select");
                if(doms && doms.length > 0){
                    doms[0].classList.remove("select");
                }
                console.log("--",doms);
            }
        }
    })

 

参考文档:https://zhuanlan.zhihu.com/p/162883371

posted @ 2023-05-02 16:01  爱美丽——  阅读(462)  评论(0)    收藏  举报