入门JS自编简单图像移动 然而并没办法执行 求解答 万分感谢!

<!DOCTYPE html>

<html>

<head>

<meta charset = "utf-8">

<title></title>

<script type="text/javascript">

window.onload = function(){

var div = document.getElementById('div');

var img = div.getElementsByTagName('img');

var ten = 10;

var input = document.getElementById('input');

input.onclick = function(){

setInterval(function(){

var left = parseInt(img[0].marginLeft);

left += ten + 'px';

},100)

}

}

</script>

<style>

#div{width:1000px; background: gray; display: block;position: absolute;}

img{width: 100px;height: 100px; display: block;position: relative;}

input{margin-top:100px;}

</style>

</head>

<body>

<div id="div">

<img src="C:\Users\Administrator\Pictures\51607230_p0.png">

</div>

<input type="button" value="click" id="input">

</body>

</html>

(不要在意图片),为什么点了Input 图不动?

KokoTa
浏览 1614回答 1
1回答

pardon110

marginLeft在js中使用错误,用style.marginLeft取值,注意:取值对象必须有相应的内联样式。关键点获取新值后,未给要移动的对象添加值。修改后的代码如下<!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title></title> <script type="text/javascript"> window.onload = function(){ var div = document.getElementById('div'); var img = div.getElementsByTagName('img'); var ten = 10; var input = document.getElementById('input'); input.onclick = function(){ setInterval(function(){ var left = parseInt(img[0].style.marginLeft); left += ten; img[0].style.marginLeft = left+"px"; },100) } } </script> <style> #div{width:1000px; background: gray; display: block;position: absolute;} img{width: 100px;height: 100px; display: block;position: relative;} input{margin-top:100px;} </style> </head> <body> <div id="div"> <img src="C:\Users\Administrator\Pictures\51607230_p0.png" style="margin-left:0px"> </div> <input type="button" value="click" id="input"> </body> </html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript