<!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 图不动?
1 回答
已采纳
pardon110
TA贡献1038条经验 获得超227个赞
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>
添加回答
举报
0/150
提交
取消