This question already has answers here:
Use CSS3 transitions with gradient backgrounds
                                
                                    (15个答案)
                                
                        
                上个月关闭。
            
        

我想更改某些transition-duration中html表中的类。

我定义了hospitalizationhospitalization2

hospitalization方面,transition-duration不能很好地工作。另一方面,在hospitalization2中,它运行良好。

为什么transition-durationhospitalization中不起作用以及如何解决?

谢谢



$(function() {
  $("td").click(function() {
    $(this).addClass("hospitalization");
  });
});

.hospitalization {
  background: linear-gradient(to bottom, aqua 49%,aqua 1%, yellow 1%, yellow 50%);
  transition-duration:0.4s;
}

.hospitalization2 {
  background-color:red;
  transition-duration:0.4s;
}

td {
  padding: 5px
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <td id="1">1</td>
  <td id="2">2</td>
  <td id="3">3</td>
  <td id="4">4</td>
  <td id="5">5</td>
  <td id="6">6</td>
  <td id="7">7</td>
  <td id="8">8</td>
  <td id="9">9</td>
  <td id="10">10</td>
</table>

最佳答案

过渡不适用于background: linear-gradient()。如果要使用background-sizebackground-position创建效果,则可以使用。

一种解决方案是使用伪元素(如:before)创建过渡效果。另外,添加一个跨度以包装每个文本,然后您可以为该文本在伪元素之前添加z-index



$(function() {
  $("td").click(function() {
    $(this).addClass("hospitalization");
  });
});

.hospitalization2 {
  background-color:red;
  transition-duration:0.4s;
}

td {
  padding: 5px;
  position: relative;
}

td span {
  position: relative;
  z-index: 1;
}

td:before {
  content: '';
  background: linear-gradient(to bottom, aqua 49%,aqua 1%, yellow 1%, yellow 50%);
  position: absolute;
  height: 100%;
  opacity: 0;
  left: 0;
  top: 0;
  transition: 0.4s;
  width: 100%;
}

td.hospitalization:before {
  opacity: 1;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <td id="1"><span>1</span></td>
  <td id="2"><span>2</span></td>
  <td id="3"><span>3</span></td>
  <td id="4"><span>4</span></td>
  <td id="5"><span>5</span></td>
  <td id="6"><span>6</span></td>
  <td id="7"><span>7</span></td>
  <td id="8"><span>8</span></td>
  <td id="9"><span>9</span></td>
  <td id="10"><span>10</span></td>
</table>

09-16 03:09