我有一个 css 转换,我需要在特定时刻让它更快。但是添加类的通常行为不起作用。我的问题是为什么没有,以及如何实现。
HTML:
<a href="#" onclick="$('div').addClass('move')">move</a> |
<a href="#" onclick="$('div').addClass('faster')">faster</a>
<div></div>
CSS:
div {
width: 100px;
height: 100px;
background-color: green;
transition: all 10s;
}
.move {
margin-left: 500px;
}
.faster {
transition: all 1s !important;
}
最佳答案
这是一个类似的问题,我们不得不处理类似的情况,但它是关于减慢动画的速度 How to slow down CSS animation on hovering element without jumps?
这个想法是依靠容器的运动来产生这种加速度。因此,为了使您的动画快速沿同一方向移动容器,但不要忘记考虑移动容器也会移动初始元素的最终目的地,因此您还需要更改它。
这是一个例子:
$('.start').click(function() {
$('.element').addClass('move');
})
$('.fast').click(function() {
$('.container').addClass('faster');
})
.container {
transition: all 5s linear;
}
.element {
margin-top: 10px;
width: 100px;
height: 100px;
background-color: green;
transition: all 10s linear;
}
.move {
margin-left: 500px;
}
.faster {
margin-left: 300px;
}
.faster .move {
margin-left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="start">move</a> | <a href="#" class="fast">faster</a>
<div class="container">
<div class="element"> </div>
</div>
<div class="element"> </div>
这个解决方案看起来很简单,因为它只依赖于一些 CSS,但它有一些缺点。你可能会注意到最后,过渡变慢了,这是由于容器的动画结束,因此元素的速度回到了它的初始值。此行为将根据点击的时刻而有所不同。
因此您可以调整值以忽略这种影响,或者您可以考虑使用更复杂的 jQuery 代码来提高速度。
这是一个例子:
$('.start').click(function() {
$('.element').addClass('move');
})
$('.fast').click(function() {
$('.element').css('margin-left','10000px'); // we make a big value to increase speed
setTimeout(function(){check_limit()},20);
})
// we test the limit and we avoid margin to go to the big value
function check_limit() {
if(parseInt($('.element').css('margin-left')) >=500) {
$('.element').css('margin-left','500px');
} else {
setTimeout(function(){check_limit()},20);
}
}
.container {
transition: all 5s linear;
}
.element {
margin-top:10px;
width: 100px;
height: 100px;
background-color: green;
transition: all 10s linear;
}
.move {
margin-left: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="start">move</a> | <a href="#" class="fast">faster</a>
<div class="element"> </div>
关于jquery - 如何即时提高 css 转换速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48497026/