如何在闭包内移动DOM元素 [英] How to move a DOM element inside a closure

查看:72
本文介绍了如何在闭包内移动DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图按照此答案使用闭包来逐步移动DOM元素.最终,我想动态创建许多应该独立移动的DOM元素,因此这就是我试图在函数内定义变量的原因.

I'm trying to use a closure as per this answer to move a DOM element incrementally. Eventually I want to dynamically create many of these DOM elements that should be moved independently, so that's why I'm trying to define the variable within the function.

给出答案的例子是

var lightning = new Array();
lightning.push($(".lightning"));

var l0 = -210;

function thunkAdd(){
  var lThis = l0;
  console.log('set lThis to '+ lThis);
  return function inc() {
    console.log('lThis = '+ lThis);
    return lThis ++;
  }
  lightning[0].css("left", lThis);
  console.log('lightning[0] left = '+lightning[0].css("left"));
}

var incrementInterval = setInterval(thunkAdd(), 33);

有关Codepen的第一个示例.在控制台中查看,看来由于某些原因console.log('lightning[0] left = '+lightning[0].css("left"));没有运行.

first example on codepen. Looking in the console, it seems that for some reason, console.log('lightning[0] left = '+lightning[0].css("left")); is not running.

我尝试过的另一种方法是:

A different approach I tried is:

var lightning = new Array();
lightning.push($(".lightning"));

var l0 = -210;
var lThis = l0;

function thunkAdd(){
  lThis ++;
  console.log('lThis = '+ lThis);

  lightning[0].css("left", lThis);
  console.log('lightning[0] left = '+lightning[0].css("left"));
}

var incrementInterval = setInterval(thunkAdd, 33);

有关代码笔的第二个示例.这样可以在屏幕上移动图像,但是理想情况下(因为下一步是动态创建和移动许多图像),我想在第一次运行时在thunkAdd函数中定义变量lThis,然后它被定义,增加它并使用lThis变量移动图像.我该怎么办?

second example on codepen. That will move the image across the screen, but ideally (because the next step is to create and move many of these images dynamically) I want to define the variable lThis inside the thunkAddfunction the first time it runs and then if it is defined, increment it and use the lThis variable to move the image. How can I do this?

推荐答案

正如注释代码中已经提到的那样,返回后将不会执行,因此您永远不会更改元素的css left属性,而只是更改变量.

As already mentioned in comments code after return will not be executed, so you never change the css left property of the element, but just increment variable.

您需要移动正在间隔执行的闭包内部的lightning[0].css("left", lThis);.

You need to move the lightning[0].css("left", lThis); inside closure that's being executed with interval.

请参见更新的示例

您还可以考虑使用jquery的动画代替(您也可以使用许多元素或循环)

You may also consider using jquery's animate instead of this (you can also do this with many elements or in loop)

$(".lightning").animate({left: '2000px'}, 10000, 'linear');

这篇关于如何在闭包内移动DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆