How to increment progressively the margin left usi

2019-08-15 19:07发布

I have an image of a black cat I want to progressively increase its width and also make the image moving from left to right increasing its own left margin. I can't understand why the width is increased and the margin-left shows NaN value.

Down here the Html :-

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Cat Walk</title>
</head>
<body>
    <img id="cat-gif" style="position:absolute;" src="http://www.anniemation.com/clip_art/images/cat-walk.gif">
    <script src="main.js"></script>
</body>

Down here the function to make move the cat:-

var catWalk = function() {

var cat = document.getElementById("cat-gif");

cat.setAttribute('width', cat.width+10); //THIS WORKS
cat.setAttribute('marginLeft', cat.marginLeft+10); //THIS DOES NOT WORK!

}

//Call to the function
window.setInterval(catWalk, 500);

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-15 19:48

Margin left is not a attribute hence it does not work in your case. its a style property hence you need to do it differently replace

cat.setAttribute('marginLeft', cat.marginLeft+10);

with

var p = cat.style.marginLeft; // return value in px; i.e 50px
p = p.substr(0,p.length-2); // remove px ie : 50px becomes 50
cat.style.marginLeft = (+p)+ 10 +'px' // convert p to number and add 10
查看更多
祖国的老花朵
3楼-- · 2019-08-15 19:55

try using the following:

cat.style.marginLeft = (parseInt((cat.style.marginLeft) || parseInt(window.getComputedStyle(cat).marginLeft))) + 10 + 'px';

instead of cat.setAttribute('marginLeft', cat.marginLeft+10); there is no attribute marginLeft by default on your Element. So you gotta go by getting the computed styles and add it to your style attribute then you can access it.

查看更多
登录 后发表回答