gpt4 book ai didi

javascript - 在没有 animate() 的情况下选择 li 时,对 div 进行动画滑动

转载 作者:行者123 更新时间:2023-12-02 14:29:31 25 4
gpt4 key购买 nike

我试图通过添加 position: absolute 来为我的顶栏设置动画<div>其中left样式属性根据所选选项卡而变化。

经过这么多尝试,如果我尝试从第二个选项卡转到第三个选项卡,我找不到不从头开始的正确方法。这个案例的主要问题在这里:

element.style.left = ((to - last) * 33 * delta) + (last * 33) + '%';

delta从 0 开始,到指示值结束。它应该从实际位置开始。

此外,我尝试从第三个选项卡转到第二个选项卡,但没有得到解决方案。

下面我粘贴plunkr我一直工作的地方。

有人可以帮我解决这个问题吗?

感谢您的建议。

最佳答案

它不起作用,因为您在动画完成后没有设置last。我在脚本中添加了一个 onComplete 回调来处理该问题。另外,两个方向的阶跃函数实际上使用相同的公式:

'use strict';

var last = 0;

function elastic(progress) {
return Math.pow(2, 10 * (progress - 1)) * Math.cos(20 * Math.PI * 1.5 / 3 * progress);
}

function linear(progress) {
return progress;
}

function quad(progress) {
return Math.pow(progress, 2);
}

function quint(progress) {
return Math.pow(progress, 5);
}

function circ(progress) {
return 1 - Math.sin(Math.acos(progress));
}

function back(progress) {
return Math.pow(progress, 2) * ((1.5 + 1) * progress - 1.5);
}

function bounce(progress) {
var a, b, result;

for (a = 0, b = 1, result; 1; a += b, b /= 2) {
if (progress >= (7 - 4 * a) / 11) {
return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2);
}
}
}

function makeEaseInOut(delta) {
return function (progress) {
if (progress < 0.5) {
return delta(2 * progress) / 2;
} else {
return (2 - delta(2 * (1 - progress))) / 2;
}
};
}

function makeEaseOut(delta) {
return function (progress) {
return 1 - delta(1 - progress);
};
}

function animate(opts) {

var start = new Date();

var id = setInterval(function () {

var timePassed = new Date() - start;

var progress = timePassed / opts.duration;

if (progress > 1) {
progress = 1;
}

var delta = opts.delta(progress);

opts.step(delta);

if (progress === 1) {
clearInterval(id);
opts.onComplete();
}

}, opts.delay);
}

function move(to) {
var element = document.getElementById('nb-line');
var delta = quint;
var duration = 400;

animate({
delay: 10,
duration: duration || 1000,
delta: delta,
step: function (delta) {
element.style.left = (((to - last) * 33 * delta) + (last * 33)) + '%';
},
onComplete: function() {
last = to;
}
});
}
.li-cont {
width: 100%;
height: 30px;
display: flex;
}
li {
list-style: none;
width: 33%;
height: 100%;
}
a {
text-align: center;
display: flex;
align-items: center;
display: block;
width: 100%;
height: 100%;
}
#nb-line {
width: 33%;
height: 5px;
background-color: blue;
position: absolute;
}
<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>

<body>
<div class="li-cont">
<li><a onclick="move(0)">1</a></li>
<li><a onclick="move(1)">2</a></li>
<li><a onclick="move(2)">3</a></li>
</div>
<div id="nb-line"></div>
</body>

</html>

关于javascript - 在没有 animate() 的情况下选择 li 时,对 div 进行动画滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37953894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com