javascript - 禁用 JQuery 自动动画

标签 javascript jquery

有时,当使用 JQuery 设置元素的 css 属性(例如“height”、“max-height”)时,它会自动将动画绑定(bind)到更改。有时它很棒,但并不总是必要的。有没有办法禁用这种动画?

实际上到底是什么情况导致JQuery自动绑定(bind)动画呢?因为我并不总是看到这种行为。我没有使用 JQuery-UI。

最佳答案

也许您要更改高度的元素有一个负责动画的 css 过渡属性。

$(function() {
  $('.myClass').css('width', '100px');
});
.myClass {
  height: 50px;
  width: 300px;
  background-color: red;
}
.transition {
  transition: width 3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
with transition
<div class="myClass transition">
</div>

without transition
<div class="myClass">
</div>

借用What is the cleanest way to disable CSS transition effects temporarily?

然后您可以创建一个来覆盖转换属性并切换该类

.notransition {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  -ms-transition: none !important;
  transition: none !important;
}

注意

如果您走这条路,您可能会遇到需要重排 css 的问题

来自What is the cleanest way to disable CSS transition effects temporarily?再次:

There are various ways to do this - see here for some. The closest thing there is to a 'standard' way of doing this is to read the offsetHeight property of the element.

One solution that actually works, then, is

$someElement.addClass('notransition'); // Disable transitions
doWhateverCssChangesYouWant($someElement);
$someElement[0].offsetHeight; // Trigger a reflow, flushing the CSS
changes $someElement.removeClass('notransition'); // Re-enable
transitions

关于javascript - 禁用 JQuery 自动动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34347598/

相关文章:

javascript - 只允许在特定时间访问网站?

javascript - 需要 Angular 2+ 货币管道显示 2 位小数并接受各种用户输入

javascript - 悬停时(或不悬停)隐藏元素的 jQuery 目标父级

javascript - 使 Div 适合整个窗口

javascript - 按类重新排序 HTML 元素,而不是按 id

javascript - jquery 单击事件在 ajax 事件后未触发

javascript - 如何根据多个条件更改数组中某项的值?

javascript - 我的 Javascript 项目正在访问网络摄像头,但没有显示任何内容

javascript - 动态下拉菜单 jQuery 内联错误

javascript - 如何使 div 向页面上的另一个元素缩小 100% 到 0%