简体   繁体   中英

How to make hover on table cells with Javascript?

I have my table with hover function on Rows, I am trying to change it to be hover on cells instead

Here's my current script:

<script type="text/javascript">
    window.onload=function(){
    var tfrow = document.getElementById('tfhover').rows.length;
    var tbRow=[];
    for (var i=1;i<tfrow;i++) {
        tbRow[i]=document.getElementById('tfhover').rows[i];
        tbRow[i].onmouseover = function(){
          this.style.backgroundColor = '#f3f8aa';
        };
        tbRow[i].onmouseout = function() {
          this.style.backgroundColor = '#ffffff';
        };
    }
};
</script>

And here what i tried to change so far but still not working:

<script type="text/javascript">
    window.onload=function(){
    var tfcell = document.getElementById('tfhover').cells.length;
    var tbCell=[];
    for (var i=1;i<tfcell;i++) {
        tbCell[i]=document.getElementById('tfhover').cells[i];
        tbCell[i].onmouseover = function(){
          this.style.backgroundColor = '#f3f8aa';
        };
        tbCell[i].onmouseout = function() {
          this.style.backgroundColor = '#ffffff';
        };
    }
};
</script>

How can i achieve hover on cell instead of hover on row with my script?

You can use regular CSS for this purpose:

#tfhover td {
    background-color: #fff;
}
#tfhover td:hover {
    background-color: #f3f8aa;
}

Thanks to @Mike Brant for pointing out the missing table id

To answer your question... which is how to do this with jQuery:

$('#tfhover td').hover(function() {
    $(this).css('background-color', '#fsf8aa');
}, function () {
    $(this).css('background-color', '#ffffff');
});

Of course your example has nothing to do with jQuery. It just reminds how much simpler these things become using jQuery.

Cells are in the list of row, as rows are in the list of table.

To get a cell, just document.getElementById('tfhover').rows[i].cells[j] .Both lists start from 0.

<script type="text/javascript">
    window.onload=function(){
    var tfrow = document.getElementById('tfhover').rows.length;
    var tbRow=[];
    for (var i=1;i<tfrow;i++) {
        tbRow[i]=document.getElementById('tfhover').rows[i];
        var tfcell=tbRow[i].cells.length;
        for(var j=0;j<tfcell;j++){
            var _tbCell=tbRow[i].cells[j];
            _tbCell.onmouseover=function(){
                this.style.backgroundColor = '#f3f8aa';
            }
            _tbCell.onmouseout=function(){
                this.style.backgroundColor = '#ffffff';
            }
        }
    }
};
</script>

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