如何使用DOM逐步增加剩余的边距 [英] How to increment progressively the margin left using DOM

查看:45
本文介绍了如何使用DOM逐步增加剩余的边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张黑猫
的图像,我想逐渐增加它的宽度,并且还要使该图像从左向右移动,以增加其自身的左边距。
我不明白为什么宽度会增加,左边距为何显示 NaN值

此处的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>

在这里使猫动的函数:-

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


推荐答案

尝试使用以下命令:

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

而不是 cat.setAttribute('marginLeft',cat.marginLeft + 10 ); 默认情况下,元素上没有属性marginLeft。因此,您必须先获取计算出的样式并将其添加到样式属性中,然后您才能访问它。

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.

这篇关于如何使用DOM逐步增加剩余的边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆