Как изменить цвет ячейки при наведении курсора

Basically when I hover over a row in my table i want the background color of the row to change to say 'black' and the specific cell or td I am hovering over to change to 'red'. Ie so two events oc...

Basically when I hover over a row in my table i want the background color of the row to change to say ‘black’ and the specific cell or td I am hovering over to change to ‘red’.

Ie so two events occur when hovering. I know how to do it for one or the other but not both.

Is this possible using jquery?

Thx to everyone for their contribution, I’ve repped you all.

asked Jul 29, 2013 at 16:04

Nuvolari's user avatar

NuvolariNuvolari

1,0915 gold badges13 silver badges29 bronze badges

2

Simple CSS is enough:

tr:hover{
 background-color:red
}

td:hover{
background-color:blue
}

http://jsfiddle.net/nRuXn/1/

cfs's user avatar

cfs

10.5k3 gold badges29 silver badges43 bronze badges

answered Jul 29, 2013 at 16:11

1

$('td').hover( function() {
    $(this).parent().children().css("background-color", "black");
    $(this).css("background-color", "red")
});

$('tr').mouseleave( function() {
    $(this).children('td').css("background-color", "white");// or whatever
});

answered Jul 29, 2013 at 16:12

Add some class to that td that you want to be red (lets call that class ‘rdClass’) and the row ‘blkClass’:

<table>
<tr class='rdClass'>
 <td>
        1
 </td>
 <td class='blkClass'>
        2
 </td>
 <td>
        3
 </td>
</tr>
</table>

$(document).ready(function () 
{
    $(".rdClass").mouseover(function ()
    {
        $(this).css("background-color", "red");
    });

    $(".blkClass").mouseover(function ()
    {
        $(this).css("background-color", "black");
    });
});

answered Jul 29, 2013 at 16:08

Armen's user avatar

ArmenArmen

1,0732 gold badges10 silver badges18 bronze badges

Add a hover listener to all rows and td’s that adds and removes a class, then use CSS to style that class differently for a row and cell.

Working Demo

jQuery

$('tr, td').hover(function() {
    $(this).addClass('highlight');
}, function() {
    $(this).removeClass('highlight');
});

CSS

tr.highlight {
    background-color: red;
}

td.highlight {
    background-color: black;
}

answered Jul 29, 2013 at 16:10

cfs's user avatar

cfscfs

10.5k3 gold badges29 silver badges43 bronze badges

If both the row and cell are in the same container, you could attach a mouseover event to that container and modify the children in the handler.

answered Jul 29, 2013 at 16:08

user2483173's user avatar

$("td").hover(function(){
  $(this).css("background-color", "red");
  $(this).parrent('tr').css("background-color", "black");
});

answered Jul 29, 2013 at 16:11

Alireza's user avatar

AlirezaAlireza

5,3199 gold badges38 silver badges50 bronze badges

$(function() {
	$(".tablecell").on('mouseover', function(event) {  
		$(".tablerow td").removeClass('hoveColBgColor hoveRowBgColor');

		$(this).parent('tr.tablerow').children('td:gt(0)').addClass('hoveRowBgColor');
		$('.tablerow > td:nth-child('+($(this).index()+1)+')').addClass('hoveRowBgColor');
		
	});
	$(".tablerow").on('mouseout', function(event) {  
		$(".tablerow").children('td:gt(0)').removeClass('hoveRowBgColor');
		$(".tablerow td").removeClass('hoveColBgColor hoveRowBgColor');
	});
});
.hoveRowBgColor{
	background-color:#ccc;
}
.hoveColBgColor{
	background-color:#666;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table id="table1" width="100%" cellspacing="1" cellpadding="0" bordercolor="" border="0">
  <tbody>
    <tr class="tablerow">
      <td class="whiteZone">&nbsp;</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone" style="width:130px;word-wrap: anywhere;">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone" style="width:130px;word-wrap: anywhere;">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone" style="width:130px;word-wrap: anywhere;">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone" style="width:130px;word-wrap: anywhere;">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
  </tbody>
</table>

answered Jul 25, 2019 at 13:02

Mrugesh Vyas's user avatar

1

Basically when I hover over a row in my table i want the background color of the row to change to say ‘black’ and the specific cell or td I am hovering over to change to ‘red’.

Ie so two events occur when hovering. I know how to do it for one or the other but not both.

Is this possible using jquery?

Thx to everyone for their contribution, I’ve repped you all.

asked Jul 29, 2013 at 16:04

Nuvolari's user avatar

NuvolariNuvolari

1,0915 gold badges13 silver badges29 bronze badges

2

Simple CSS is enough:

tr:hover{
 background-color:red
}

td:hover{
background-color:blue
}

http://jsfiddle.net/nRuXn/1/

cfs's user avatar

cfs

10.5k3 gold badges29 silver badges43 bronze badges

answered Jul 29, 2013 at 16:11

1

$('td').hover( function() {
    $(this).parent().children().css("background-color", "black");
    $(this).css("background-color", "red")
});

$('tr').mouseleave( function() {
    $(this).children('td').css("background-color", "white");// or whatever
});

answered Jul 29, 2013 at 16:12

Add some class to that td that you want to be red (lets call that class ‘rdClass’) and the row ‘blkClass’:

<table>
<tr class='rdClass'>
 <td>
        1
 </td>
 <td class='blkClass'>
        2
 </td>
 <td>
        3
 </td>
</tr>
</table>

$(document).ready(function () 
{
    $(".rdClass").mouseover(function ()
    {
        $(this).css("background-color", "red");
    });

    $(".blkClass").mouseover(function ()
    {
        $(this).css("background-color", "black");
    });
});

answered Jul 29, 2013 at 16:08

Armen's user avatar

ArmenArmen

1,0732 gold badges10 silver badges18 bronze badges

Add a hover listener to all rows and td’s that adds and removes a class, then use CSS to style that class differently for a row and cell.

Working Demo

jQuery

$('tr, td').hover(function() {
    $(this).addClass('highlight');
}, function() {
    $(this).removeClass('highlight');
});

CSS

tr.highlight {
    background-color: red;
}

td.highlight {
    background-color: black;
}

answered Jul 29, 2013 at 16:10

cfs's user avatar

cfscfs

10.5k3 gold badges29 silver badges43 bronze badges

If both the row and cell are in the same container, you could attach a mouseover event to that container and modify the children in the handler.

answered Jul 29, 2013 at 16:08

user2483173's user avatar

$("td").hover(function(){
  $(this).css("background-color", "red");
  $(this).parrent('tr').css("background-color", "black");
});

answered Jul 29, 2013 at 16:11

Alireza's user avatar

AlirezaAlireza

5,3199 gold badges38 silver badges50 bronze badges

$(function() {
	$(".tablecell").on('mouseover', function(event) {  
		$(".tablerow td").removeClass('hoveColBgColor hoveRowBgColor');

		$(this).parent('tr.tablerow').children('td:gt(0)').addClass('hoveRowBgColor');
		$('.tablerow > td:nth-child('+($(this).index()+1)+')').addClass('hoveRowBgColor');
		
	});
	$(".tablerow").on('mouseout', function(event) {  
		$(".tablerow").children('td:gt(0)').removeClass('hoveRowBgColor');
		$(".tablerow td").removeClass('hoveColBgColor hoveRowBgColor');
	});
});
.hoveRowBgColor{
	background-color:#ccc;
}
.hoveColBgColor{
	background-color:#666;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table id="table1" width="100%" cellspacing="1" cellpadding="0" bordercolor="" border="0">
  <tbody>
    <tr class="tablerow">
      <td class="whiteZone">&nbsp;</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
      <td class="whiteZone">head</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone" style="width:130px;word-wrap: anywhere;">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone" style="width:130px;word-wrap: anywhere;">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone" style="width:130px;word-wrap: anywhere;">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
    <tr class="tablerow">
      <td class="menuZone" style="width:130px;word-wrap: anywhere;">head</td>
      <td class="whiteZone tablecell" id="tablecell_1" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_13" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_4" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_3" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_2" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_12" align="center">test</td>
      <td class="whiteZone tablecell" id="tablecell_18" align="center">test</td>
    </tr>
  </tbody>
</table>

answered Jul 25, 2019 at 13:02

Mrugesh Vyas's user avatar

1

Несколько способов как сделать выделение ячеек таблицы при наведении курсора. Во всех примерах верстка таблиц будет стандартная, без лишних классов:

<table class="table">
	<thead>
		<tr>
			<th>RU</th>
			<th>FR</th>
			<th>US Men</th>
			<th>US Women</th>
			<th>UK</th>
			<th>Длина</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>35.5 RU</td>
			<td>36</td>
			<td>4</td>
			<td>5</td>
			<td>3.5</td>
			<td>22.1</td>
		</tr>
		<tr>
			<td>36 RU</td>
			<td>36 2/3</td>
			<td>4.5</td>
			<td>5.5</td>
			<td>4</td>
			<td>22.5</td>
		</tr>
		<tr>
			<td>36.5 RU</td>
			<td>37 1/3</td>
			<td>5</td>
			<td>6</td>
			<td>4.5</td>
			<td>22.9</td>
		</tr>
		...
	</tbody>
</table>

HTML

1

Выделение ячейки

.table {
	border-collapse: collapse;
	border-spacing: 0;
	width: 100%;
}
.table th, .table td {
	border: 1px solid #888;
	padding: 10px;
	text-align: center;
	vertical-align: middle;
	position: relative;
}

.table td:hover {
	background: #fffabe;
}
.table td:hover:after {
	content: '';
	position: absolute;
	top: 0px;
	right: 0px; 
	bottom: 0px;    
	left: 0px;
	border: 3px solid orange;
}

CSS

2

Выделение строки

.table {
	border-collapse: collapse;
	border-spacing: 0;
	width: 100%;
}
.table th, .table td {
	border: 1px solid #888;
	padding: 10px;
	text-align: center;
	vertical-align: middle;
	position: relative;
}

.table tr:hover td {
	background: #fffabe;
}
.table tr:hover td:after {
	content: '';
	position: absolute;
	top: 0px;
	right: 0px;    
	bottom: 0px;    
	left: 0px;
	width: 105%;
	border-top: 3px solid orange;
	border-bottom: 3px solid orange;
}

/* Рамка слева у первой ячейки */
.table tr:hover td:first-child:after {
	border-left: 3px solid orange;
}

/* Рамка справа у последний ячейки */
.table tr:hover td:last-child:after {
	border-right: 3px solid orange;
	width: auto;
}

CSS

3

Выделение столбца

В данном варианте применен JQuery, который по индексу наведенного элемента добавляет class="hover" всем ячейкам в столбце.

$(document).ready(function() {
	$('.table th, .table td').hover(function() {
		var t = parseInt($(this).index()) + 1;
		$('th:nth-child(' + t + '),td:nth-child(' + t + ')').addClass('hover');
	}, function() {
		var t = parseInt($(this).index()) + 1;
		$('th:nth-child(' + t + '),td:nth-child(' + t + ')').removeClass('hover');
	});
});

JS

.table {
	border-collapse: collapse;
	border-spacing: 0;
	width: 100%;
}
.table th, .table td {
	border: 1px solid #888;
	padding: 10px;
	text-align: center;
	vertical-align: middle;
	position: relative;
}
.table tbody .hover {
	background: #fffabe;
}
.table tbody .hover:after {
	content: '';
	position: absolute;
	top: 0px;
	right: 0px;    
	bottom: 0px;    
	left: 0px;
	height: 105%;
	border-left: 3px solid orange;
	border-right: 3px solid orange;
}

/* Рамка сверху у первой ячейки */
.table tbody tr:first-child .hover:after {
	border-top: 3px solid orange;
}

/* Рамка снизу у последней ячейки */
.table tbody tr:last-child .hover:after {
	border-bottom: 3px solid orange;
	height: auto;
}

CSS

4

Выделение строк и столбцов

.table {
	border-collapse: collapse;
	border-spacing: 0;
	width: 100%;
	overflow: hidden;
}
.table th, .table td {
	border: 1px solid #888;
	padding: 10px;
	text-align: center;
	vertical-align: middle;
	position: relative;
}
.table th, .table td {
	border: 1px solid #888;
	padding: 10px;
	text-align: center;
	vertical-align: middle;
	position: relative;
}
.table td:hover {
	background: #fffabe;
}

.table td:hover:before { 
	background-color: #eee;
	content: '';  
	height: 100%;
	left: -5000px;
	position: absolute;  
	top: 0;
	width: 10000px;   
	z-index: -2;        
}

.table td:hover:after { 
	background-color: #eee;
	content: '';  
	height: 10000px;    
	left: 0;
	position: absolute;  
	top: -5000px;
	width: 100%;
	z-index: -1;        
}

CSS

I have looked through all the answers posted but I cant seem to get this code to work correctly. I am trying to get the individual cell to change color when I hover over it, but I don’t have access to the .css with the service we are using. I am being forced to drop an HTML code box that I can paste my code into specific to the element I am changing, but not the entire .css file…just that element.

Here is my code. Any help in getting the background to change to #ff0000 and the Text to change to #000000 when I roll over the cell would be greatly appreciated.

(It is ultimately my intent to add a >a href for each of the cells as well, but I am trying to do this one step at a time. The >a href will (I hope) add the selected cell to a shopping cart.)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<title></title>

<style type="text/css">
body {
      background: #000;   
}
#wrap {
     margin: 0 auto; /* margin 0 auto will center that box in your document */
     width: 780px; /*size of your box*/
     background: #000;
     text-align: center; /* everything will be written in that box will be centered horizontally*/
     }
</style>
<div id="wrap">
  <table width="780">
     <tr>
        <td align="center">
<table border=1>
  <tbody>
    <!-- Results table headers -->
    <tr>
      <th>Messages Per Month</th>
      <th>1 Month Pricing</th>
      <th>3 Month Pricing</th>
      <th>12 Month Pricing</th>
    </tr>
    <tr>
      <td>500</td>
      <td>$14.95/Month</td>
      <td>$12.95/Month</td>
      <td>$9.95/Month</td>
    </tr>
    <tr>
      <td>1,000</td>
      <td>$24.95/Month</td>
      <td>$20.95/Month</td>
      <td>$17.95/Month</td>
    </tr>
    <tr>
      <td>1,500</td>
      <td>$37.95/Month</td>
      <td>$31.95/Month</td>
      <td>$26.95/Month</td>
    </tr>
    <tr>
      <td>2,000</td>
      <td>$49.95/Month</td>
      <td>$41.95/Month</td>
      <td>$35.95/Month</td>
    </tr>
    <tr>
      <td>2,500</td>
      <td>$62.95/Month</td>
      <td>$52.95/Month</td>
      <td>$44.95/Month</td>
    </tr>
    <tr>
      <td>5,000</td>
      <td>$119.95/Month</td>
      <td>Not Available</td>
      <td>Not Available</td>
    </tr>
    <tr>
      <td>7,500</td>
      <td>$179.95/Month</td>
      <td>Not Available</td>
      <td>Not Available</td>
    </tr>
    <tr>
      <td>10,000</td>
      <td>$219.95/Month</td>
      <td>Not Available</td>
      <td>Not Available</td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>
        </td>
     </tr>
   </table>
</div>

Brian Tompsett - 汤莱恩's user avatar

asked Jul 30, 2012 at 23:47

user1564352's user avatar

1

In CSS:

td:hover {
  background-color: #ff0000;
  color: #000000;
}

Or you can use JavaScript/jQuery:

$(document).ready(function() {
  $("td").hover(
    function() {
      $(this).css('background-color', '#ff0000');
      $(this).css('color', '#000000');
    }, 
    function() {
      $(this).css('background-color', 'none');
      $(this).css('color', 'black'); // or whatever your original color was
    }
  );
});

answered Jul 31, 2012 at 1:01

Jon's user avatar

JonJon

9668 silver badges22 bronze badges

2

Wrap the cell data with a div (class=»cell_hvr») and a link around the content.

.cell_hvr {
    padding: 2px;
    width: 100%;
    height: 100%;
}
.cell_hvr a {
    display: block;
    text-decoration: none;
}
.cell_hvr a:hover {
    background-color: red;
}

<div class="cell_hvr"><a href="#" target="_blank"> (Your content) </a></div>

answered Aug 10, 2015 at 11:57

reese_thebeast's user avatar

You can do this by giving each cell a class

<td class="a">..</td>

and then styling it

<style>
  td.a { background-color:#ff0000; }
  td.a:hover { background-color:#000000; }
</style>

chopper's user avatar

chopper

6,5196 gold badges36 silver badges53 bronze badges

answered Jun 25, 2017 at 2:30

RAuTeSH's user avatar

1

CSS: td:hover, th:hover { background:#ff0000; color:#000; }

answered Jul 30, 2012 at 23:50

Mark Pieszak - Trilon.io's user avatar

I was looking for the JavaScript version of the answer to this question. But, I am not using JQuery..

I have
oCell = newRow.insertCell();
oCell.style.background = tintTest(myCounts[i]);

myCounts is just an array holding an Int..

but now i just wanted to add the hover background color to my current oCell before smashing it in line and moving on with the loop……
So I found the code below as the only checked answer in a stream of ‘can’t be done’.. just not sure if this would even help me.

var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName('head')[0].appendChild(style);

EDIT!!! I just found out my issue (I hope the code snip helps with yours still) I tried to add the hover in CSS and it just isn’t supported at all.

answered Oct 26, 2017 at 21:37

Dill Pickle's user avatar

I have looked through all the answers posted but I cant seem to get this code to work correctly. I am trying to get the individual cell to change color when I hover over it, but I don’t have access to the .css with the service we are using. I am being forced to drop an HTML code box that I can paste my code into specific to the element I am changing, but not the entire .css file…just that element.

Here is my code. Any help in getting the background to change to #ff0000 and the Text to change to #000000 when I roll over the cell would be greatly appreciated.

(It is ultimately my intent to add a >a href for each of the cells as well, but I am trying to do this one step at a time. The >a href will (I hope) add the selected cell to a shopping cart.)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<title></title>

<style type="text/css">
body {
      background: #000;   
}
#wrap {
     margin: 0 auto; /* margin 0 auto will center that box in your document */
     width: 780px; /*size of your box*/
     background: #000;
     text-align: center; /* everything will be written in that box will be centered horizontally*/
     }
</style>
<div id="wrap">
  <table width="780">
     <tr>
        <td align="center">
<table border=1>
  <tbody>
    <!-- Results table headers -->
    <tr>
      <th>Messages Per Month</th>
      <th>1 Month Pricing</th>
      <th>3 Month Pricing</th>
      <th>12 Month Pricing</th>
    </tr>
    <tr>
      <td>500</td>
      <td>$14.95/Month</td>
      <td>$12.95/Month</td>
      <td>$9.95/Month</td>
    </tr>
    <tr>
      <td>1,000</td>
      <td>$24.95/Month</td>
      <td>$20.95/Month</td>
      <td>$17.95/Month</td>
    </tr>
    <tr>
      <td>1,500</td>
      <td>$37.95/Month</td>
      <td>$31.95/Month</td>
      <td>$26.95/Month</td>
    </tr>
    <tr>
      <td>2,000</td>
      <td>$49.95/Month</td>
      <td>$41.95/Month</td>
      <td>$35.95/Month</td>
    </tr>
    <tr>
      <td>2,500</td>
      <td>$62.95/Month</td>
      <td>$52.95/Month</td>
      <td>$44.95/Month</td>
    </tr>
    <tr>
      <td>5,000</td>
      <td>$119.95/Month</td>
      <td>Not Available</td>
      <td>Not Available</td>
    </tr>
    <tr>
      <td>7,500</td>
      <td>$179.95/Month</td>
      <td>Not Available</td>
      <td>Not Available</td>
    </tr>
    <tr>
      <td>10,000</td>
      <td>$219.95/Month</td>
      <td>Not Available</td>
      <td>Not Available</td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>
        </td>
     </tr>
   </table>
</div>

Brian Tompsett - 汤莱恩's user avatar

asked Jul 30, 2012 at 23:47

user1564352's user avatar

1

In CSS:

td:hover {
  background-color: #ff0000;
  color: #000000;
}

Or you can use JavaScript/jQuery:

$(document).ready(function() {
  $("td").hover(
    function() {
      $(this).css('background-color', '#ff0000');
      $(this).css('color', '#000000');
    }, 
    function() {
      $(this).css('background-color', 'none');
      $(this).css('color', 'black'); // or whatever your original color was
    }
  );
});

answered Jul 31, 2012 at 1:01

Jon's user avatar

JonJon

9668 silver badges22 bronze badges

2

Wrap the cell data with a div (class=»cell_hvr») and a link around the content.

.cell_hvr {
    padding: 2px;
    width: 100%;
    height: 100%;
}
.cell_hvr a {
    display: block;
    text-decoration: none;
}
.cell_hvr a:hover {
    background-color: red;
}

<div class="cell_hvr"><a href="#" target="_blank"> (Your content) </a></div>

answered Aug 10, 2015 at 11:57

reese_thebeast's user avatar

You can do this by giving each cell a class

<td class="a">..</td>

and then styling it

<style>
  td.a { background-color:#ff0000; }
  td.a:hover { background-color:#000000; }
</style>

chopper's user avatar

chopper

6,5196 gold badges36 silver badges53 bronze badges

answered Jun 25, 2017 at 2:30

RAuTeSH's user avatar

1

CSS: td:hover, th:hover { background:#ff0000; color:#000; }

answered Jul 30, 2012 at 23:50

Mark Pieszak - Trilon.io's user avatar

I was looking for the JavaScript version of the answer to this question. But, I am not using JQuery..

I have
oCell = newRow.insertCell();
oCell.style.background = tintTest(myCounts[i]);

myCounts is just an array holding an Int..

but now i just wanted to add the hover background color to my current oCell before smashing it in line and moving on with the loop……
So I found the code below as the only checked answer in a stream of ‘can’t be done’.. just not sure if this would even help me.

var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName('head')[0].appendChild(style);

EDIT!!! I just found out my issue (I hope the code snip helps with yours still) I tried to add the hover in CSS and it just isn’t supported at all.

answered Oct 26, 2017 at 21:37

Dill Pickle's user avatar

0 / 0 / 0

Регистрация: 08.11.2014

Сообщений: 4

1

Смена фона при наведении курсора в строке таблицы

08.11.2014, 16:10. Показов 9704. Ответов 9


Здравствуйте.

Нужна ваша помощь, так как, почитав форум, для решения данной проблемы ничего не нашел.

Ситуация следующая: имеется таблица.

Код

<table widht="374" cellpadding="0" cellspacing="0" class="test">
<tr align="center" height="15">
<td width="50">25</td>
<td width="9" background="/img/l1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="47" background="/img/1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/2.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="9" background="/img/c1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/3.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/3.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/3.png" bgcolor="#e8e8e8"></td>
<td width="9" background="/img/c2.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/4.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/5.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="10" background="/img/r1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="50" height="18">25</td>
</tr>
</table>

Требуется, чтобы при наведении курсора на строку менялся ее фон. Все бы ничего, но бэкграунды внутри ячеек портят всю картину. Как быть? есть возможность пошаманить с z-indexом?

Спасибо большое за помощь.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



12 / 12 / 2

Регистрация: 29.03.2011

Сообщений: 69

08.11.2014, 16:18

2

Почему через CSS оформление не задано?



0



0 / 0 / 0

Регистрация: 08.11.2014

Сообщений: 4

08.11.2014, 16:20

 [ТС]

3

Почему через CSS оформление не задано?

долгая история. так было бы проще решить проблему? ок, если так — переверстаю



0



Fedor92

Эксперт HTML/CSS

2960 / 2578 / 1068

Регистрация: 15.12.2012

Сообщений: 9,733

Записей в блоге: 11

08.11.2014, 19:41

4

Как раз бэкграунды Вам в помощь, а также волшебный псевдокласс hover и никакие z-index не нужны…
Небольшой пример:

HTML5
1
2
3
4
5
6
7
8
9
10
<html>
<head></head>
<style>
.cell{width:100px; height:100px; background-color:red}
.cell:hover{background-color:green}
</style>
<body> 
<div class="cell"></div>
</body>
</html>



0



3 / 3 / 0

Регистрация: 31.08.2014

Сообщений: 25

08.11.2014, 20:11

5

Если тебе надо , чтобы при наведении курсора на строку менялся ее фон ячейки то вот код

<!doctype html>
<html>
<head>
<meta charset=»utf-8″>
<style type=»text/css»>
td:hover {
background-color: red ;<!— При наведении меняет цвет фона —>
}

</style>
<title>lab</title>
</head>
<body>
<table widht=»374″ cellpadding=»0″ cellspacing=»0″ class=»test»>
<tr align=»center» height=»15″>
<td width=»50″>25</td>
<td width=»9″ background=»/img/l1.png» bgcolor=»#e8e8e8″>&nbsp;</td>/* При наведении меняет цвет фона*/
<td width=»47″ background=»/img/1.png» bgcolor=»#e8e8e8″>&nbsp;</td>
<td width=»48″ background=»/img/2.png» bgcolor=»#e8e8e8″>&nbsp;</td>
<td width=»9″ background=»/img/c1.png» bgcolor=»#e8e8e8″>&nbsp;</td>
<td width=»48″ background=»/img/3.png» bgcolor=»#e8e8e8″>&nbsp;</td>
<td width=»48″ background=»/img/3.png» bgcolor=»#e8e8e8″>&nbsp;</td>
<td width=»48″ background=»/img/3.png» bgcolor=»#e8e8e8″></td>
<td width=»9″ background=»/img/c2.png» bgcolor=»#e8e8e8″>&nbsp;</td>
<td width=»48″ background=»/img/4.png» bgcolor=»#e8e8e8″>&nbsp;</td>
<td width=»48″ background=»/img/5.png» bgcolor=»#e8e8e8″>&nbsp;</td>
<td width=»10″ background=»/img/r1.png» bgcolor=»#e8e8e8″>&nbsp;</td>
<td width=»50″ height=»18″>25</td>
</tr>
</table>
</body>
</html>



0



chomovva

61 / 59 / 23

Регистрация: 29.07.2014

Сообщений: 285

08.11.2014, 20:23

6

Цитата
Сообщение от kf-prk-1984
Посмотреть сообщение

Если тебе надо , чтобы при наведении курсора на строку менялся ее фон ячейки то вот код

так будет менять только в одной ячейке.

если правильно понял вопрос, то лучше так, во всей строке меняться буде цвет:

HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<html>
<head>
    <style>
    .test tr:hover td {
        background-color:red}
    </style>
</head>
<body>
 
 
<table widht="374" cellpadding="0" cellspacing="0" class="test">
<tr align="center" height="15">
<td width="50">25</td>
<td width="9" background="/img/l1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="47" background="/img/1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/2.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="9" background="/img/c1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/3.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/3.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/3.png" bgcolor="#e8e8e8"></td>
<td width="9" background="/img/c2.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/4.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/5.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="10" background="/img/r1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="50" height="18">25</td>
</tr>
<tr align="center" height="15">
<td width="50">25</td>
<td width="9" background="/img/l1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="47" background="/img/1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/2.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="9" background="/img/c1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/3.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/3.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/3.png" bgcolor="#e8e8e8"></td>
<td width="9" background="/img/c2.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/4.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="/img/5.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="10" background="/img/r1.png" bgcolor="#e8e8e8">&nbsp;</td>
<td width="50" height="18">25</td>
</tr>
</table>
 
 
</body>
</html>



0



0 / 0 / 0

Регистрация: 08.11.2014

Сообщений: 4

09.11.2014, 11:59

 [ТС]

7

большое спасибо за ответы, но вы не совсем поняли суть проблемы.

как видно из кода, в каждой ячейке в строке (кроме первой и последней) уже есть бэкграунд, заданный картинкой, соответственно, там смена фона цветом не проходит, он меняется только на первой и на последней ячейке.

вот тут и затык :-(



0



61 / 59 / 23

Регистрация: 29.07.2014

Сообщений: 285

09.11.2014, 12:08

8

Цитата
Сообщение от posho
Посмотреть сообщение

большое спасибо за ответы, но вы не совсем поняли суть проблемы.
как видно из кода, в каждой ячейке в строке (кроме первой и последней) уже есть бэкграунд, заданный картинкой, соответственно, там смена фона цветом не проходит, он меняется только на первой и на последней ячейке.
вот тут и затык :-(

меняется

Смена фона при наведении курсора в строке таблицы

может я тебя неправильно понял? нарисуй.



0



0 / 0 / 0

Регистрация: 08.11.2014

Сообщений: 4

09.11.2014, 12:11

 [ТС]

9

вот оно как выходит

Миниатюры

Смена фона при наведении курсора в строке таблицы
 



0



chomovva

61 / 59 / 23

Регистрация: 29.07.2014

Сообщений: 285

09.11.2014, 12:14

10

извините, немного ошибся
еще одну строчку добавить нужно

HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<html>
<head>
    <style>
    .test tr:hover td {
        background-color:red;
        background-image:none;}
    </style>
</head>
<body>
 
 
<table widht="374" cellpadding="0" cellspacing="0" class="test">
<tr align="center" height="15">
<td width="50">25</td>
<td width="9" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="47" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="9" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8"></td>
<td width="9" background="1.jpgg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="10" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="50" height="18">25</td>
</tr>
<tr align="center" height="15">
<td width="50">25</td>
<td width="9" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="47" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="9" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8"></td>
<td width="9" background="1.jpgg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="48" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="10" background="1.jpg" bgcolor="#e8e8e8">&nbsp;</td>
<td width="50" height="18">25</td>
</tr>
</table>
 
 
</body>
</html>



0



ролловер эффект excel лого

В сегодняшней статье мы рассмотрим, как с помощью небольшого макроса и условного форматирования создать ролловер эффект в Excel. Данный эффект используется для подсвечивания элемента при наведении мышки на кнопку или ссылку. В нашем случае мы реализуем работу Excel таким образом, чтобы при наведении курсора на ячейку, цвет фона менялся.

Данная технология описана на сайте Джордана Голдмайера optionexplicitvba

Зачем вообще использовать ролловер эффект? Основная идея в том, чтобы отобразить какую-нибудь информацию или выделить элемент интерфейса во время наведения на него мышкой. В первом случае данный функционал уже реализован с помощью комментариев. Но в поддержку данной методики скажу, что комментирование ограничено теми инструментами, которые предоставляет нам Excel, в то время как написание макросов ограничено лишь нашей фантазией. Плюс ко всему, данную технику можно использовать для реализации интересных дизайнерских решений.

Итак, преступим. Нам понадобится функция ГИПЕРССЫЛКА, которая создает ссылку и позволяет перейти на документ или страницу, находящуюся на сетевом диске или интернет. Данная функция имеет следующий синтаксис:

ГИПЕРССЫЛКА(адрес, [имя])

где,

Адрес – путь или имя открываемого документа. Может быть как адресом на жестком диске, так и URL сайта.

Имя – необязательный аргумент, текст ссылки, под которым мы можем скрыть адрес.

В ячейке B3, к которой мы хотим применить ролловер эффект, вводим следующую формулу:

=ГИПЕРССЫЛКА(RollOverEffect(); «Наведи курсор»)

ролловер эффект excel

Excel выдаст нам ошибку, не обращайте пока на нее внимание.

Далее создаем пользовательскую функцию. Для этого переходим в редактор VBA. (О редакторе VBA, вы можете прочитать в статье про создание макросов в Excel.)  И вставляем следующий код:

1
2
3

Public Function RollOverEffect()
Range(«A1»).Value = «Курсор наведен!»
End Function

ролловер эффект excel

Данный код будет вызываться функцией ГИПЕРССЫЛКА, каждый раз, как на ячейку будет наведен курсор. Теперь вернитесь в книгу и поместите мышь на ячейку B3. Наша пользовательская функция отработает свой код, и в ячейке A1 вы увидите надпись Курсор наведен!

Чтобы избежать выдачи ошибки #ЗНАЧ!, немного модернизируем нашу формулу и воспользуемся функцией ЕСЛИОШИБКА. Формула примет следующий вид:

=ЕСЛИОШИБКА(ГИПЕРССЫЛКА(RollOverEffect(); «Наведи курсор»); «Наведи курсор»)

Вот и все, если вы найдете интересное применение данной технике, не стесняйтесь, опишите его в комментариях, мы обязательно обсудим.

Напоследок, пример того как я использовал данную технику для подсвечивания ячейки, над которой находится курсор:

ролловер эффект excel

Скачать файл с примером применения ролловер эффекта в excel

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить цвет ячейки на основании значения другой ячейки
  • Как изменить цвет ячейки vba excel
  • Как изменить цвет ячейки datagridview
  • Как изменить цвет ячеек таблицы html
  • Как изменить цвет ярлыков на телефоне

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии