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,这点需要注意。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | <!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> |
效果图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库