JavaScript - Как я могу изменить цвет фона на всех TD в TR одновременно на Mouseover / Mouseout? - PullRequest
8 голосов
/ 03 августа 2011

Когда я mouseover один TD в ряду, я хочу, чтобы все TD одновременно изменили цвет фона, затем включите mouseout.

Как мне это сделать?

Ответы [ 11 ]

14 голосов
/ 03 августа 2011

В CSS вы можете сделать

tr td { background-color: white }
tr:hover td { background-color: black };

или просто

tr { background-color: white }
tr:hover { background-color: black };

если у тдс нет собственного цвета фона.

Оба должны сделать строку черным при наведении курсора, и белым в противном случае.

Конечно, вы также можете сделать это в Javascript, но в этом нет необходимости (за исключением IE6, который не понимает псевдокласс :hover ни на чем, кроме тегов <a>)

5 голосов
/ 29 июля 2015
<table border="1" cellpadding="5" cellspacing="0">
    <tr>
        <th></th>
        <th>Water</th>
        <th>Air</th>
        <th>Fire</th>
        <th>Earth</th>
    </tr>
    <tr onmouseover="ChangeBackgroundColor(this)" onmouseout="RestoreBackgroundColor(this)">
        <td>Spring thunderclouds</td>
        <td>Yes</td>
        <td>Yes</td>
        <td>No</td>
        <td>No</td>
    </tr>
    <tr onmouseover="ChangeBackgroundColor(this)" onmouseout="RestoreBackgroundColor(this)">
        <td>Roasting chestnuts</td>
        <td>No</td>
        <td>No</td>
        <td>Yes</td>
        <td>Yes</td>
    </tr>
    <tr onmouseover="ChangeBackgroundColor(this)" onmouseout="RestoreBackgroundColor(this)">
        <td>Winter snowbanks</td>
        <td>Yes</td>
        <td>Yes</td>
        <td>No</td>
        <td>Yes</td>
    </tr>
    <tr onmouseover="ChangeBackgroundColor(this)" onmouseout="RestoreBackgroundColor(this)">
        <td>Ice cream on a hot summer day</td>
        <td>Yes</td>
        <td>Yes</td>
        <td>Yes</td>
        <td>Yes</td>
    </tr>
</table>
<script type="text/javascript">
    // Specify the normal table row background color
    //   and the background color for when the mouse 
    //   hovers over the table row.

    var TableBackgroundNormalColor = "#ffffff";
    var TableBackgroundMouseoverColor = "#9999ff";

    // These two functions need no customization.
    function ChangeBackgroundColor(row) {
        row.style.backgroundColor = TableBackgroundMouseoverColor;
    }

    function RestoreBackgroundColor(row) {
        row.style.backgroundColor = TableBackgroundNormalColor;
    }
</script>
5 голосов
/ 03 августа 2011
var tds = document.getElementsByTagName("td");
for(var i = 0; i < tds.length; i++) {
    tds[i].onmouseover = function() {
       this.parentNode.style.backgroundColor = "#ff0000";
    }
    tds[i].onmouseout = function() {
      this.parentNode.style.backgroundColor = "#fff";  
    }
}

Это на самом деле меняет цвет фона родительского tr, а не каждого td, но его можно легко изменить для этого. Вы также можете прикрепить события к элементам tr вместо элементов td, и тогда вам не придется использовать parentNode, но я не знаю, нужно ли вам делать другие вещи в обработчике событий конкретно относится к td.

2 голосов
/ 03 августа 2011

Я не знаю, какой у вас точный вариант использования, но для таких задач я бы использовал только CSS:

td {
    background: #f00; }
tr:hover td {
    background: #fc0; }

http://jsfiddle.net/feeela/53JBV/

1 голос
/ 03 августа 2011
<td onmouseover="changeColorTo(this.parentNode, put color here)" onmouseout="changeColorTo(this.parentNode, put color here)">
...
<script>
    function changeColorTo(parent, color)
    {
        var i, tdArray = parent.getElementsByTagName('td');
        for(i in tdArray)
        {
            tdArray[i].style.backgroundColor = color;
        }
    }
</script>

Это быстрее, чем при использовании jQuery, также не все используют jQuery.

0 голосов
/ 06 апреля 2017

Когда я делал это во всех сценариях Java, я делал это так

<!DOCTYPE html>
<html>
<head>
<title>Chapter 11 Problem 1</title>
<script>
function blueText()
{
var paragraphObject = document.
getElementById("Paragraph");
paragraphObject.style.color = 'blue',
paragraphObject.style.background= 'white';
}

function whiteText()
{
var paragraphObject = document.
getElementById("Paragraph");
paragraphObject.style.color = 'white',
paragraphObject.style.background = 'blue';
}
</script>

</head>
<body>
<p id="Paragraph" style = "color:white; background-color:blue";
onmouseover="blueText()" onmouseout="whiteText()">
Paragraph Text
</p>
</body>
</html>

Я действительно надеюсь, что это не искажает все это

0 голосов
/ 03 августа 2011
<style type="text/css">
.table1 tr:hover td{
    background-color:#ccc;
}
</style>
<table class="table1">
    <tr>
        <td>cell 1-1</td>
        <td>cell 1-2</td>
        <td>cell 1-3</td>
        <td>cell 1-4</td>
    </tr>
    <tr>
        <td>cell 2-1</td>
        <td>cell 2-2</td>
        <td>cell 2-3</td>
        <td>cell 2-4</td>
    </tr>
    <tr>
        <td>cell 2-1</td>
        <td>cell 2-2</td>
        <td>cell 2-3</td>
        <td>cell 2-4</td>
    </tr>
</table>
0 голосов
/ 03 августа 2011

Если вы хотите независимое от фреймворка решение, вы можете попробовать это:

function highlightCells(tableRow) {
    for (var index = 0; index < tableRow.childNodes.length; index++) {
        var row = tableRow.childNodes[index];
        if (row.style) {
            row.style.backgroundColor = "red";
        }
    }
}

function unhighlightCells(tableRow) {
    for (var index = 0; index < tableRow.childNodes.length; index++) {
        var row = tableRow.childNodes[index];
        if (row.style) {
            row.style.backgroundColor = "white";
        }
    }
}

Пример: http://jsfiddle.net/9nh9a/

Хотя, если говорить практически, не проще ли привязать слушателя к элементам <tr> вместо элементов <td>? Есть ли какая-то причина, по которой вы хотите слушать только элементы <td>?

0 голосов
/ 03 августа 2011

Этот jsFiddle , который я создал, показывает, как это сделать с помощью jQuery.

Я использую событие jQuery hover для обработки того, что вы пытаетесь сделать.

0 голосов
/ 03 августа 2011

В jQuery:

$('td').mouseover(function( obj ) {
    $(obj).parent().children().css("background-color","green");
});

$('td').mouseout(function( obj ) {
    $(obj).parent().children().css("background-color","red");
});

Или в Javascript:

var tds = document.getElementsByTagName( "td" );

for( var i = 0; i < tds.length; i++ ) {
    tds[i].addEventListener("mouseover",function(){
        var children = this.parentNode.getElementsByTagName("td");

        for( var j = 0; j < children.length; j++ )
            children[j].style.background-color = "green";
    });

    tds[i].addEventListener("mouseout",function(){
        var children = this.parentNode.getElementsByTagName("td");

        for( var j = 0; j < children.length; j++ )
            children[j].style.background-color = "red";
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...