一:行内样式:
var mario=document.getElementById(“mario”);
var left=mario.style.left;
二.非行内样式
var mario2=document.getElementById(“mario2”);
var left2=mario2.currentStyle?mario2.currentStyle[‘left’]:getComputedStyle(mario2,null)[‘left’]
在这里插入代码片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<style>
body{margin:0;padding:0;}
#wrap{
width:500px;
height:300px;
background:skyblue;
}
#mario2{
width:100px;height:100px;left:10px;top:120px;position:absolute;
}
</style>
<script>
function Mario(){
this.move=function (val){
var mario=document.getElementById("mario");
var mario2=document.getElementById("mario2");
var left=mario.style.left;
var left2=mario2.currentStyle?mario2.currentStyle['left']:getComputedStyle(mario2,null)['left']
alert(left2);
left=Number(left.substr(0,left.length-2))
var width=mario.style.width;
width=Number(width.substr(0,width.length-2))
switch(val){
case 1:
if(left+width>=500){
alert('已到达边界,不能再移动');
}else if(left+width>480&&left+width<500){
mario.style.left='400px';
}
else{
mario.style.left=(left+20)+'px';
}
break;
case 0:
if(left<=0){
alert('已到达边界,不能再移动');
}else if(0<left&&left<20){
mario.style.left='0px';
}else{
mario.style.left=(left-20)+'px';
}
break;
}
}
}
var mario=new Mario();
</script>
<body>
<div id="wrap">
<img id="mario" style='width:100px;height:100px;left:10px;top:10px;position:absolute;' src="image/1.jpg"/>
<img id="mario2" src="image/1.jpg"/>
</div>
<div id="controlcenter"><input type="button" value="向右移动" onclick="mario.move(1)"/></div>
<div id="controlcenter"><input type="button" value="向左移动" onclick="mario.move(0)"/></div>
</body>
</html>