gpt4 book ai didi

javascript - 如何让一个嵌入式函数运行多次

转载 作者:行者123 更新时间:2023-11-30 13:21:43 25 4
gpt4 key购买 nike

我的问题是如何让一个函数的多个实例运行。下面是我的功能 - 一个简单的淡入淡出功能。我遇到的问题是,当它第二次被调用时,它放弃了第一次调用。因此,如果用户单击一个按钮,它将显示一条淡出的消息。

如果用户点击另一个按钮,之前的淡入淡出消息将停止在当前的不透明度级别。

?

什么是停止机制?之前的功能哪里去了?

函数

function newEffects(element, direction, max_time ) 
{
newEffects.arrayHold = [];
newEffects.arrayHold[element.id] = 0;

function next()
{
newEffects.arrayHold[element.id] += 10;
if ( direction === 'up' )
{
element.style.opacity = newEffects.arrayHold[element.id] / max_time;
}
else if ( direction === 'down' )
{
element.style.opacity = ( max_time - newEffects.arrayHold[element.id] ) / max_time;
}
if ( newEffects.arrayHold[element.id] <= max_time )
{
setTimeout( next, 10 );
}
}
next();
return true;
};

召唤

newEffects(this.element, 'down', 4000 ); 

旧对象

/**
* Effects - causes all elements that are fading to sync. to same opacity level as they share the same elapsed time.
*/

var Effects = function( element )
{
this.element = element;
};

Effects.prototype.fade = function( direction, max_time )
{
Effects.elapsed = 0;
var persist_element = this.element;
function next()
{
Effects.elapsed += 10;
if ( direction === 'up' )
{
persist_element.style.opacity = Effects.elapsed / max_time;
}
else if ( direction === 'down' )
{
persist_element.style.opacity = ( max_time - Effects.elapsed ) / max_time;
}
if ( Effects.elapsed <= max_time )
{
setTimeout( next, 10 );
}
}
next();
return true;
};

最佳答案

试试这个

function newEffects(element, direction, max_time ) 
{
var mt=max_time;
var dir=direction;
var el=document.getElementById(element);
var newEffects={};
newEffects.arrayHold = [];
newEffects.arrayHold[el.id] = 0;

function next()
{
newEffects.arrayHold[el.id] += 10;
if ( dir === 'up' )
{
el.style.opacity = newEffects.arrayHold[el.id] / mt;
}
else if ( dir === 'down' )
{
el.style.opacity = ( mt - newEffects.arrayHold[el.id] ) / mt;
}
if ( newEffects.arrayHold[el.id] <= mt )
{
setTimeout( next, 10 );
}
} next();
};

一个例子是 here .

Declare every variable using var keyword inside the parent function to keep separate instance of each items, this is how clouser works.

关于javascript - 如何让一个嵌入式函数运行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10056620/

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