gpt4 book ai didi

javascript - js中的全局变量,如何避免

转载 作者:行者123 更新时间:2023-12-01 03:28:22 26 4
gpt4 key购买 nike

我有一个 change() 函数,它使用 setInterval() 来重复动画:

function change(){
interval = setInterval(c,300);
function c(){...}
c()
}

c() 函数完成这项工作。我还有一个 stop() 函数,可以停止所有动画并恢复初始情况:

function stop(){
clearInterval(interval);
...
};

我读到最好使用 var 关键字而不是声明全局变量。但如果我这样做,我无法从 stop() 函数访问 interval 。在 change() 函数之外声明 interval 也会给我带来一个问题。

好吧,我正在尝试本·阿斯顿提出的最后一个解决方案。代码如下:

function Animator() {
var id;

return {
start: start,
stop: stop,
};

function start() {
id = requestAnimationFrame(go);
}

function stop() {
clearAnimationFrame(id);
}

function go() {
// increment the animation
for (var i=0;i<img.length;i++){
var num = randNum(0,img.length-1)
var btn = img[i].nextSibling.nextSibling.childNodes[1]
img[i].setAttribute("src",img_path[num].path);
$(btn).css({"background-color":img_path[num].color,"border":"4px solid"+img_path[num].color});
$(img[i]).animate({width: "-=80px", height: "-=80px"},'slow');
$(img[i]).animate({width: "+=80px", height: "+=80px"},'slow')}

id = requestAnimationFrame(go)
}


}

基本上,当用户按下按钮时,图像开始改变其宽度、高度以及颜色。 这是剩下的:

var animator = new Animator();

function stop(){ //fn related to the stop button
animator.stop()};


function change(){ //fn related to the start button
animator.start()}

我不知道如何正确使用requestAnimationFrame,我现在正在研究它。但是当我按下开始按钮时,图像只改变一次,然后就停止了。在前面的代码中,我有一个 for 循环来完成这项工作:

function change(){

interval = setInterval(c,300);
function c(){
for (var i=0;i<img.length;i++){
var num = randNum(0,img.length-1)
var btn = img[i].nextSibling.nextSibling.childNodes[1]
img[i].setAttribute("src",img_path[num].path);
$(btn).css({"background-color":img_path[num].color,"border":"4px solid"+img_path[num].color});
$(img[i]).animate({width: "-=80px", height: "-=80px"},'slow');
$(img[i]).animate({width: "+=80px", height: "+=80px"},'slow')}}
c()}

我承认我不太清楚如何实现 go func?谢谢

编辑:现在它可以工作了(我正在处理另一个文件:))但是我的停止按钮有问题

最佳答案

您也可以使用 Closure,请阅读此处的文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures使用 Closure,您可以定义私有(private)和公共(public)函数。

关于javascript - js中的全局变量,如何避免,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44663289/

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