0

私はこのコードを使用しています:

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をクリックし、600pxに達するまで一度に10ピクセルずつ左にdivを移動することです。

今、私はこれを間違った方法で行っていますか?

現時点で私は

Uncaught ReferenceError: keep_moving is not defined
4

3 に答える 3

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

ちなみに、leftstyleプロパティはそれを右に移動します(要素が左からどれだけ離れているかです)

于 2012-05-16T00:42:07.167 に答える
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

あなたはあなたに答えるのに間違った方法でそれについて行っています。

あなたは非常に多くの間隔を生み出していて、すぐにあなたのウェブページを殺します。次のようなロジックを試す必要があります。

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 に答える