js中修改css样式两种方法

一:行内样式:
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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值