简体   繁体   中英

How can I change the row and colum background-color on hover a table element?

the big problem was to change the column background-color, because the columns is not an element on HTML.

I solved that problem using a simple tr:hover to change the row background-color and some javascript code to solve the column color problem.

First Stage (CSS): // change the background-color from a row on hover.

tr:hover{
 background: #414141;
}

Second Stage (JavaScript): // change the background-color from a colum on hover.

let items = document.querySelectorAll('td')
let rows = document.querySelectorAll('tr')

items.forEach(function(item){
    item.onmouseover = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                row.children[item.cellIndex].style.background = '#393939'
            }
        })
    }
    item.onmouseout = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                row.children[item.cellIndex].style.background = '#414141'
            }
        })
    }
})

That solution worked, but when I change a style property it seems to lose the hover property of that element. So, I created a dictionary to save the element style.

Third Stage (JavaScript): // change the background-color from a colum on hover. Without lose any style property:

let items = document.querySelectorAll('td')
let rows = document.querySelectorAll('tr')
var aux = {}

items.forEach(function(item){
    item.onmouseover = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                aux[item.cellIndex] = row.children[item.cellIndex].style
                row.children[item.cellIndex].style.background = '#393939'
            }
        })
    }
    item.onmouseout = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                row.children[item.cellIndex].style = aux[item.cellIndex]
            }
        })
    }
})

I don't know if this is the best way to solve the problem, but worked to me. Tell me if you got that on another way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM