Frage

I am trying to change the margin of each element, using setAttribute.

How can I able to use my variable dist "distance" to decrease value until 10, every after delay "interval"?

var dist=200; var speed = 2000;

function slideLeft(x){
    dist--; 
    slideSet[x].setAttribute("style","margin-right:"+dist+"px;");   
    setTimeout(slideLeft(x), delay);    
}

Take these style and elements for example...

.widiv { margin-right:200px; }

<div>
    <div class="widiv" ></div>
    <div class="widiv" ></div>
</div>

Thanks a lot.

War es hilfreich?

Lösung

Here's your code with some changes: See fiddle http://jsfiddle.net/chrismoutray/4p3xX/

var dist = 200, delay = 500,
    slideSet = document.getElementsByTagName('div');

function slideLeft(x) {
    dist--;
    if (dist < 0) return;
    slideSet[x].setAttribute("style", "margin-right:" + dist + "px;");
    setTimeout(function() {
        slideLeft(x);
    }, delay);
}

slideLeft(1);

With a few additions to the styling:

.widiv { 
    margin-right:200px; 
    float:left; 
    width: 100px; 
    border: 1px solid black; 
    height: 100px; }

The main differences are that when calling setTimeout I'm using a function delegate (function() { <your code here> }) to call the slideLeft method so that x variable is used correctly - I don't think you can pass a statement into setTimeout without doing it this way.

Also in styling the divs I made sure to include a float left other wise the change to margin right doesn't make sense - should this be margin left instead?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top