gpt4 book ai didi

javascript - 功能需要比预期更长的时间才能完成

转载 作者:行者123 更新时间:2023-11-29 21:16:17 25 4
gpt4 key购买 nike

我创建了一个简单的滑动函数,它应该使元素在给定的时间内出现或消失。

我构建此函数的公式是: ms = 1 pixel / (initial size / duration) ,本质上是计算在减去 1px 之前应该经过多少毫秒 来自元素的 height width .

我的数学逻辑表明该函数应在 1000ms 内完成,但对我来说,完成所需的时间看起来要多得多,但不确定有多少。

为什么比 1s花费的时间更长 完成以及可能导致它的原因是什么?

代码:

/* ----- JavaScript ----- */
function slide(el, duration, direction) {
/* Default */
duration = duration || 1000, direction = direction || "vertical";

var
dim = (direction === "horizontal") ? "width" : "height",

/* Get how tall or wide el is in 'px' */
size = initSize = parseFloat(
getComputedStyle(el, null).getPropertyValue(dim) || el.style[dim]
),

/* Get the previous size, so as to restore el to it */
prevSize = el.style["prev" + dim] || 0,

/* Calculating how many ms should pass before subtracting 1px*/
ms = 1 / (initSize / duration),

interval = setInterval(function() {
/* If el is visible */
if (initSize > prevSize && size > prevSize) el.style[dim] = --size + "px";

/* If el is not visible */
else if (prevSize > initSize && size <= prevSize) el.style[dim] = ++size + "px";

/* Clear the interval when 0 is reached and cache the previous size */
else {
console.log("oops")
el.style["prev" + dim] = initSize;
clearInterval(interval);
}
}, ms);
}

slide(document.getElementById("a"));
<!----- HTML ----->
<div id = "a" style = "width: 200px;height: 300px;background-color:black;"></div>

最佳答案

您需要调整步长,即每次迭代要添加/删除的像素数,并调整延迟时间。以下是改进版本,大约需要 1.1 秒。

function slide(el, duration, direction) {
/* Default */
duration = duration || 1000, direction = direction || "vertical";

var dim = (direction === "horizontal") ? "width" : "height",

/* Get how tall or wide el is in 'px' */
size = initSize = parseFloat(
getComputedStyle(el, null).getPropertyValue(dim) || el.style[dim]
),

/* Get the previous size, so as to restore el to it */
prevSize = el.style["prev" + dim] || 0;

/* Calculating how many ms should pass before subtracting 1px*/
var step = 1;
var ms = 1 / (initSize / duration)
if(ms<10){
ms=10;
step = 10*(initSize/duration);
console.log(ms,step)
}
var now=new Date();
var interval;var i=0;
var animate = function() {
i++;
interval=setTimeout(animate,ms);
/* If el is visible */
if (initSize > prevSize && size > prevSize) el.style[dim] = (size=size-step) + "px";

/* If el is not visible */
else if (prevSize > initSize && size <= prevSize) el.style[dim] = (size=size+step) + "px";

/* Clear the interval when 0 is reached and cache the previous size */
else {
console.log("oops", new Date()-now,size,step,i)
el.style["prev" + dim] = initSize;
clearInterval(interval);
}
};
//var interval = setInterval(animate, ms);
animate();
}
slide(document.getElementById("a"));

关于javascript - 功能需要比预期更长的时间才能完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39313283/

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