【问题标题】:Why does an element's width change after animation ends?为什么动画结束后元素的宽度会发生变化?
【发布时间】:2019-08-23 20:11:15
【问题描述】:

我正在学习 jQuery,测试它的功能,但我做的一个例子有些问题。

https://codepen.io/MaxVelichkin/pen/pBJeZy

/*remove animate2 class and assign animate1 class to target*/
$(function() {
  $('#trigger').on('click', function() {
    $('#target').removeClass('animate2');
    $('#target').addClass('animate1');
  });
});

/*remove animate1 class and assign animate2 class to target*/
$(function() {
  $('#trigger2').on('click', function() {
    $('#target').removeClass('animate1');
    $('#target').addClass('animate2');
  });
});
/*just a container around*/

#container {
  margin: 10px;
  width: 350px;
  height: 350px;
  border: solid green 1px;
}


/*green button*/

#trigger {
  width: 50px;
  height: 50px;
  border-radius: 100%;
  background-color: green;
  margin: 20px auto;
}


/*red button*/

#trigger2 {
  width: 50px;
  height: 50px;
  border-radius: 100%;
  background-color: red;
  margin: 20px auto;
}


/*Target div which will be changing*/

#target {
  width: 100px;
  height: 100px;
  border: solid blue 1px;
  margin: 10px auto;
}


/*Keyframes for green button*/

@keyframes myfirst {
  0% {
    background: white;
    width: 100px;
    height: 100px;
    border-radius: 0%;
  }
  100% {
    background: blue;
    width: 150px;
    border-radius: 100%;
  }
}


/*Keyframes for red button*/

@keyframes mysecond {
  0% {
    background: blue;
    width: 150px;
    border-radius: 100%;
  }
  100% {
    background: white;
    width: 100px;
    height: 100px;
    border-radius: 0%;
  }
}


/*cusstom class to be assigned by green button*/

.animate1 {
  -webkit-animation: myfirst 3s;
  animation: myfirst 3s;
  height: 100px;
  background: blue;
  width: 150px;
  border-radius: 100%;
  margin: 10px auto;
}


/*cusstom class to be assigned by red button*/

.animate2 {
  -webkit-animation: mysecond 3s;
  animation: mysecond 3s;
  height: 100px;
  width: 150px;
  border: solid red 1px;
  border-radius: 0%;
  margin: 10px auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="trigger"></div>
  <div id="trigger2"></div>
  <div id="target"></div>
</div>

有:

  • 2 个按钮,绿色和红色。
  • 2 组关键帧。
  • 2 个自定义类,用于启动相应关键帧的动画并应用最后一个关键帧的样式。
  • 目标 div,我想在按钮单击时更改哪种样式。

当我单击按钮时,它会为目标 div 分配一个类并删除由另一个按钮分配的类。

问题一:为什么绿色按钮动画结束后目标div的宽度又变回100px(为什么不是150px)?

问题 2:我做的一切都是正确的还是有更好的 jQuery 方法?

【问题讨论】:

  • 这里的一个很好的教训是,在 CSS 中应该很少使用 ID。最好依赖可重用的类(一组类似的东西),即使它是一组。这使得你的 CSS 更少依赖于标记,并且更容易根据优先级来破译。

标签: javascript jquery html css


【解决方案1】:

您的 #target 优先,因为它是一个 id 选择器。它的宽度为100px。您的课程 animate1 被覆盖,这就是您看不到 150px 的原因。

【讨论】:

  • 非常感谢你,珍妮弗!
【解决方案2】:

你可以像这个动画那样编码:myfirst 3s forwords;

【讨论】:

  • 完全不清楚您建议的解决方案是什么。
猜你喜欢
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 2021-02-21
  • 2022-06-23
  • 2018-09-13
  • 1970-01-01
  • 2022-07-29
  • 2021-07-21
相关资源
最近更新 更多