最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - tr onmouse events - Stack Overflow

programmeradmin0浏览0评论

I want to be able to hover on a row and highlight all of it but I am having an issue with the code below since some cells have a different background.

 <tr style="" onmouseover="this.style.background='Red';" onmouseout="this.style.background='#595959'" >

That is fine all all cells have the same background but if I click a cell it highlights it and onmouseout="this.style.background='#595959'" will always reset it.

How can I change that to something like:

onmouseout="this.style.background='currentCellBGColor"

I want to be able to hover on a row and highlight all of it but I am having an issue with the code below since some cells have a different background.

 <tr style="" onmouseover="this.style.background='Red';" onmouseout="this.style.background='#595959'" >

That is fine all all cells have the same background but if I click a cell it highlights it and onmouseout="this.style.background='#595959'" will always reset it.

How can I change that to something like:

onmouseout="this.style.background='currentCellBGColor"
Share Improve this question edited Jun 15, 2012 at 16:45 Colin Brock 21.6k9 gold badges49 silver badges62 bronze badges asked Jun 15, 2012 at 16:41 sd_draculasd_dracula 3,89629 gold badges91 silver badges165 bronze badges 1
  • I would think that it would be easier to just add and remove a class rather than store and retrieve the specific style. – j08691 Commented Jun 15, 2012 at 16:46
Add a ment  | 

2 Answers 2

Reset to default 4

It can be done with a pure CSS solution. No JavaScript needed

Pure CSS solution that will work in IE8+ all other modern day browsers

tr:hover td { background-color:yellow }
td.selected { background-color: green; }
tr:hover td.selected { background-color: lime; }

Fiddle

If you need IE7, you need to add a class onmosueover to the table row and remove the class onmouseout.

tr:hover td, tr.hover td { background-color:yellow }
td.selected { background-color: green; }
tr:hover td.selected, tr.hover td.selected { background-color: lime; }

Even if I agree that is better to make it with css hover, I like to answer to the question, how to do it with javascript.

You can save it on one attribute and use it to restore it as:

<script>
function setBackground(me, color)
{
   me.setAttribute("data-oldback", me.style.background);       
   me.style.background=color;
}

function restoreBackground(me)
{
    me.style.background = me.getAttribute("data-oldback");
}    
</script>

and

  <tr onmouseover="setBackground(this, 'Red');" 
   onmouseout="restoreBackground(this);" 
     style="background:blue;" >

and a test : http://jsfiddle/AdDgS/3/ and this http://jsfiddle/AdDgS/4/

发布评论

评论列表(0)

  1. 暂无评论