JS while循环后未定义Clearinterval名称

时间:2012-05-16 00:28:45

标签: javascript

我正在使用此代码:

var s_wrap = document.getElementById('slider');
var s_list = document.getElementById('slider-list');
var li_items = s_list.getElementsByTagName("li");
var next = document.getElementById('next');
var pos, item_w, refreshIntervalId;

next.onclick = function() { 
    item_w = window.getComputedStyle(li_items[0],null).getPropertyValue("width").split('px')[0]; 
    move('left', li_items[0], 10, item_w);
};

var move = function(direction, el, increment, amount) {
    while(pos <= amount){
        keep_moving = setInterval(function(){
            pos = el.style[direction].split('px')[0];
            if(pos == '') pos = 0;
            pos = parseInt(pos) + increment;
            el.style[direction] = pos + 'px';
        }, 100);
    }
    clearInterval(keep_moving); 

};

代码的基本要点是,单击一个div,一次将div向左移动10个像素,直到达到600px。

现在我是以错误的方式解决这个问题吗?

此刻我得到了

Uncaught ReferenceError: keep_moving is not defined

3 个答案:

答案 0 :(得分:1)

var move = function(direction, el, increment, amount) {
    var keep_moving; // <=============

    while(pos <= amount){
        keep_moving = setInterval(function(){
            pos = el.style[direction].split('px')[0];
            if(pos == '') pos = 0;
            pos = parseInt(pos) + increment;
            el.style[direction] = pos + 'px';
        }, 100);
    }
    clearInterval(keep_moving); 

};

虽然我必须说代码对我来说没有多大意义。

答案 1 :(得分:1)

SetInterval重复执行任务。正确的方法是

function move(direction, el, increment, amount) {
    var pos = parseFloat(el.style[direction]) || 0;
    var repeated = function(){
        el.style[direction] = pos + "px";
        pos += increment;
        if(pos < amount) setTimeout(repeated, 100);
    }
    repeated();
}

顺便说一句,left样式属性将其移动到右侧(元素应该从左侧移动多远)

答案 2 :(得分:1)

你是以错误的方式回答你。

您正在产生如此多的间隔,并会迅速杀死您的网页。你应该尝试这样的逻辑:

var move = function(direction, el, increment, amount) {
    pos = el.style[direction].split('px')[0];
    if(pos == '') pos = 0;
    pos = parseInt(pos) + increment;
    if(pos > amount) { return; }
    el.style[direction] = pos + 'px';
    window.setTimeout(function() { move(direction, el, increment, amount); },100);
};
相关问题