将当前CSS值保存在变量中而不更改

时间:2018-05-15 08:02:10

标签: jquery css

我正在尝试将元素的当前CSS值保留在变量中。我的问题是每当我改变原始元素的样式时,我在变化之前赋予的变量中的值也是如此。

var currentColor;

$("tr").hover(function () {
    currentColor = $(this).css("background-color");
    $(this).css("background-color", "#f7f7f7")
}).mouseout(function () {
    $(this).css("background-color", currentColor);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr style="background-color:#FF0000"><td>Foo</td></tr>
    <tr style="background-color:#00FF00"><td>Foo</td></tr>
    <tr style="background-color:#0000FF"><td>Foo</td></tr>
</table>

我也尝试使用.data(),但它没有解决我的问题。

var currentColor;

$("tr").hover(function () {
    $("div").data("currentColor", $(this).css("background-color"));
    $(this).css("background-color", "#f7f7f7")
}).mouseout(function () {
    $(this).css("background-color", $("div").data("currentColor"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr style="background-color:#FF0000"><td>Foo</td></tr>
    <tr style="background-color:#00FF00"><td>Foo</td></tr>
    <tr style="background-color:#0000FF"><td>Foo</td></tr>
</table>

更新

由于社区问我为什么没有使用tr:hover {background:color}我必须在我的实际项目中包含它,在那种特殊情况下,我遇到了一种情况,我必须使用jQuery修改背景颜色。之后tr:hover {background:color}不起作用,您还必须使用jQuery管理tr:hover功能。

我将这部分排除在我的问题之外,因为我认为没有必要对其进行解释。

2 个答案:

答案 0 :(得分:5)

使用此代码:

$("tr").mouseenter(function() {
  $(this).attr("currentColor", $(this).css("background-color"));
  $(this).css("background-color", "#f7f7f7")
}).mouseout(function() {
  $(this).css("background-color", $(this).attr("currentColor"));
});

我不知道您使用$("div")的原因,因为您的HTML中没有div

其次,使用mouseenter而非hover

jQuery演示

&#13;
&#13;
$("tr").mouseenter(function() {
  $(this).attr("currentColor", $(this).css("background-color")).css("background-color", "#f7f7f7")
}).mouseout(function() {
  $(this).css("background-color", $(this).attr("currentColor"));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr style="background-color:#FF0000">
    <td>Foo</td>
  </tr>
  <tr style="background-color:#00FF00">
    <td>Foo</td>
  </tr>
  <tr style="background-color:#0000FF">
    <td>Foo</td>
  </tr>
</table>
&#13;
&#13;
&#13;

Css Way演示

&#13;
&#13;
table tbody tr:hover td {
  background-color: #f7f7f7;
}
&#13;
<table>
  <tr style="background-color:#FF0000">
    <td>Foo</td>
  </tr>
  <tr style="background-color:#00FF00">
    <td>Foo</td>
  </tr>
  <tr style="background-color:#0000FF">
    <td>Foo</td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用PURE CSS

&#13;
&#13;
td:hover{
background-color:#f7f7f7;
}
&#13;
<table>
  <tr style="background-color:#FF0000">
    <td>Foo</td>
  </tr>
  <tr style="background-color:#00FF00">
    <td>Foo</td>
  </tr>
  <tr style="background-color:#0000FF">
    <td>Foo</td>
  </tr>
</table>
&#13;
&#13;
&#13;

您可以在此处找到css中的解释:hover https://www.w3schools.com/cssref/css_selectors.asp