0

I'm using this code:

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); 

};

So basic gist of the code is, click a div, move a div left by 10 pixels at a time until it reaches 600px.

Now am I going about this the wrong way?

At the moment I get a

Uncaught ReferenceError: keep_moving is not defined
4

3 回答 3

1

You are going about it the wrong way to answer you.

You are spawning so many intervals and will quickly kill your web page. You should try logic like so:

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);
};
于 2012-05-16T00:45:57.183 回答
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); 

};

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

于 2012-05-16T00:32:52.577 回答
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样式属性将它向右移动(它是元素应该离左边多远)

于 2012-05-16T00:42:07.167 回答