我有一张黑猫的图片
我想逐渐增加它的宽度,并使图像从左向右移动,增加它自己的左边距。
我不明白为什么宽度增加并且 margin-left 显示 NaN value
。
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。因此,您必须获取计算出的样式并将其添加到您的样式属性中,然后您才能访问它。
关于javascript - 如何使用 DOM 逐步增加剩余边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51081571/