简体   繁体   English

JavaScript悬停效果删除了预定义的样式

[英]Javascript hover effect removes pre defined style

I am using a tutorial from Imar Spaanjaars' web site to make an entire table row clickable and have a hover effect on it also. 我正在使用Imar Spaanjaars网站上教程来使整个表格行都可单击,并对其具有悬停效果。 Once the user hovers over the table row it removes the pre defined background color for that row. 用户将鼠标悬停在表格行上方时,它将删除该行的预定义背景色。 I want to make it so that way it does not overwrite this style. 我要制作它,以便它不会覆盖此样式。 How might I do that? 我该怎么办?

    <script type="text/javascript">
    function ChangeColor(tableRow, highLight)
    {
    if (highLight)
    {
      tableRow.style.backgroundColor = '#dcfac9';
    }
    else
    {
      tableRow.style.backgroundColor = 'white';
    }
  }

  function DoNav(theUrl)
  {
  document.location.href = theUrl;
  }
  </script>

If you have any better suggestions to accomplish this task I would love to hear them! 如果您有更好的建议来完成此任务,我将很乐意听到他们的建议!

My tr tag has a bgcolor tag in it that is set by my php if that specific piece of mail has been read or not. 我的tr标签中有一个bgcolor标签,由我的php设置,如果该特定邮件已被读取或未读取。

If the original background color is specified via a stylesheet or (as in your case) a legacy bgcolor attribute, then you can just clear out the style on the element when you're done, and it'll revert: 如果通过样式表或旧的bgcolor属性指定了原始背景色,则只需在完成操作后清除元素上的样式,然后它将还原:

function ChangeColor(tableRow, highLight)
{
  if (highLight)
  {
    tableRow.style.backgroundColor = '#dcfac9';
  }
  else
  {
    tableRow.style.backgroundColor = '';
  }
}

That said, you'd probably be better off using a CSS class and associated rules to represent the highlighted state of the row and add/remove that as you like: 也就是说,最好使用CSS类和关联的规则来表示行的突出显示状态,并根据需要添加/删除该状态:

tr { backgroundColor: <whatever> }
tr.highlighted { backgroundColor: #dcfac9 }

Then your Javascript becomes 然后你的JavaScript变成

function ChangeColor(tableRow, highLight) {
    if(highLight) 
    {
        tableRow.className = 'highlighted';
    } 
    else 
    {
        tableRow.className = '';
    }
}

In addition to keeping specific styles out of your script and markup (where they become difficult to maintain over time), this lets you add or change hover styles (say, bold text, or a border) without adding complexity to the code. 除了将特定样式保留在脚本标记之外(随着时间的推移它们将变得难以维护),这还使您可以添加或更改悬停样式(例如,粗体文本或边框),而不会增加代码的复杂性。

If you have access to a Javascript library such as Prototype , Ext.js or Dojo , then you can use their class manipulation functions instead, which will handle the case where you want to preserve an existing className, or are using multiple classes for on a single element. 如果您可以访问PrototypeExt.jsDojo之类的Javascript库,则可以改用它们的类操作函数,该函数可以处理要保留现有className的情况,或者在一个上使用多个类的情况。单个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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