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 21px 2px 上間距 高度 邊框寬度 */
		top:-33px; 
		background-color:yellow;
	}
	.box3{
		/* 10px +21px + 2px 上間距 高度 邊框寬度 */
		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>

  

 效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM