html+css+js 更换div位置

前言:
主要用 getComputedStyle() 来获得元素的最终样式,element.style 获得的样式只能是内联样式,像是 style标签内的就取不到。

兼容性:
在 Chrome 和 Firefox 是支持该属性的,同时 IE 9 10 11 也是支持相同的特性的,IE 8并不支持这个特性。 IE 8 支持的是 element.currentStyle 这个属性,这个属性返回的值和 getComputedStyle 的返回基本一致,只是在 float 的支持上,IE 8 支持的是 styleFloat,这点需要注意。

代码:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" initial-scale="1" charset="utf-8" />
<title>Document</title>
<style>
	.outerBox{
		position:relative;
		left:50%;
		width:900px;
		height:300px;
		margin-left:-450px;
		border:0;
		padding:0;
		background-color:pink;
	}
	.box {
		position:relative;
		width:100%;
		height:21px;
		padding:0;
		margin-top:10px;
		text-align:left;
		border-style:solid;
		border-width:1px;
		transition: top 2s;
		-moz-transition: top 2s;	/* Firefox 4 */
		-webkit-transition: top 2s;	/* Safari 和 Chrome */
		-o-transition: top 2s;	/* Opera */
	}
	.box1{
		/* 10px */
		top:66px;
		background-color:red;
	}
	.box2{
		/* 10px + 30px */
		top:-33px; 
		background-color:yellow;
	}
	.box3{
		/* 10px +30px +10px +*/
		top:-33px; 
		background-color: blue;
	}
</style>
</head>
<body>
	<div class="outerBox">
		<div class ="box box1">我是一号,和原来的三号换了位置,top值=10(margin-top)+2(border-width*2)+21(box.width))*2px</div>
		<div class ="box box2">我是二号,和原来的一号换了位置,top值=-(10(margin-top)+2(border-width*2)+21(box.width))px</div>
		<div class ="box box3">我是三号,和原来的二号换了位置,top值=-(10(margin-top)+2(border-width*2)+21(box.width))px</div>
	</div>
	<div>
		<input type="button" onclick="move(0,0)" value="点我" />
		<input type="button" onclick="move(2,1)" value="点我" />
	</div>
	偏门知识:
	<a href="https://www.runoob.com/w3cnote/window-getcomputedstyle-method.html">window.getComputedStyle() 方法的使用</a>
</body>
<script>
	function move_up(n,el){
		var m = window.getComputedStyle(el).top;
		m = m.replace("px","");
		m = Number(m);
		//console.log(window.getComputedStyle(el).top);
		el.style.top=m + n*-33+'px';
		
	}
	function move_down(n,el){
		var m = window.getComputedStyle(el).top;
		m = m.replace("px","");
		m = Number(m);
		el.style.top=m + n*33+'px';
		
	}

	function move(n,m){
		var boxs = document.getElementsByClassName('box');
		//console.log(boxs);
		if(m<1){
			move_up(1,boxs[n]);
		}else{
			//console.log(n);
			move_down(1,boxs[n]);
		}
	}
</script>

</html>

  

 效果图:

猜你喜欢

转载自www.cnblogs.com/Dmail/p/13173663.html