奇怪的javascript行为,这里会发生什么?
考虑以下javascript函数:奇怪的javascript行为,这里会发生什么?,javascript,google-chrome,Javascript,Google Chrome,考虑以下javascript函数: function bs_animate_percentage(elem,style,unit,from,to,time) { if(!elem) return; console.log("first elem", elem); var start = new Date().getTime(), timer = setInterval(function() { console.log("secon
function bs_animate_percentage(elem,style,unit,from,to,time) {
if(!elem) return;
console.log("first elem", elem);
var start = new Date().getTime(),
timer = setInterval(function() {
console.log("second elem", elem);
console.log("time", time);
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+unit;
if(step == 1) clearInterval(timer);
},25);
elem.style[style] = from+unit;
}
此函数应设置加载条的动画,它取自另一个stackOverflow问题。我还想给动画添加一个文本更改,为此我需要初始元素的父元素
当我使用以下参数运行此函数时,控制台会记录以下值:
bs_animate_percentage(document.getElementById("progress-bar"), 'width', '%', 0, 100, 60000);
*** LOGS ***
"first elem", <div....> (the selected div)
"second elem", undefiend
"time", 600000
bs_animate_百分比(document.getElementById(“进度条”)、“宽度”、“百分比”、0、100、60000);
***日志***
“第一要素”(所选部门)
“第二要素”,未定义
“时间”,60万
基本上,在main函数中,elem是已知的,并且具有预期的值。但是在匿名函数中,elem以未定义的状态注销,如果我尝试获取它的父元素,它也未定义,但是,style属性按预期工作,如中所示,elem的宽度正在更改。我在chrome中遇到过这种情况,这里会有什么问题
编辑:我也检查了Firefox,但奇怪的是,在第二个控制台日志中返回了正确的结果。这一定是Chrome特有的东西,但我不知道
EDIT2:更奇怪的是,当试图在JSFIDLE中复制这种行为时,无论是在Chrome还是Firefox中,这种行为都不会持续。那么我应该在哪里查找问题呢?我很确定elem变量在这段时间内没有设置。 我的预测是它有时可能会过去。 验证这一点的方法之一如下:
function bs_animate_percentage(elem,style,unit,from,to,time) {
if(!elem) return;
console.log("first elem", elem);
var x = elem.cloneNode(true);
var start = new Date().getTime(),
timer = setInterval(function() {
console.log("second elem", x);
console.log("time", time);
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+unit;
if(step == 1) clearInterval(timer);
},25);
elem.style[style] = from+unit;
}
我相信这会好的。这将证实你的问题。
接下来是如何解决这个问题。
elem是dom元素还是其他元素?
它是用铬改性的吗?
更好的方法是给这个元素一个id,然后根据id获取它,并按如下方式设置它的样式,仅当您不希望调试代码中的问题时
function bs_animate_percentage(elem,style,unit,from,to,time) {
if(!elem) return;
console.log("first elem", elem);
var x = elem.cloneNode(true).id;
var start = new Date().getTime(),
timer = setInterval(function() {
// Or some similar logic
x = document.getElementById(x);
console.log("second elem", x);
console.log("time", time);
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+unit;
if(step == 1) clearInterval(timer);
},25);
elem.style[style] = from+unit;
}