讓你的網(wǎng)頁動起來:Javascript+CSS拖曳盒子指南
更新時間:2024年03月19日 08:37:45 作者:遠近高低各不同
想讓你的網(wǎng)頁動起來嗎?這份Javascript+CSS拖曳盒子指南將帶你進入網(wǎng)頁交互設計的奇妙世界,跟著我們的步驟,你很快就能創(chuàng)建出令人眼前一亮的動態(tài)網(wǎng)頁效果,準備好開啟一段有趣的編程探索之旅吧!
讓我為大家?guī)硪粋€小案例吧!
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> * { margin: 0; padding: 0; } .box1 { width: 100px; height: 100px; background-color: black; margin-bottom: 10px; position: relative; left: 0; top: 0; } .box2 { width: 100px; height: 100px; background-color: pink; margin-bottom: 10px; margin-left: 200px; } .box3 { width: 100px; height: 100px; background-color: orange; margin-top: 120px; margin-left: 200px; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> <div class="box3"></div> </body> <script> //獲取要移動的盒子 var div = document.querySelector(".box1") //獲取其他2個盒子 var div1=document.querySelector(".box2") var div2=document.querySelector(".box3") div.onmousedown = function(e){ //獲取盒子距離頁面多少 var divX =div.offsetLeft var divY =div.offsetTop //獲取盒子點擊的xy坐標 var downX =e.clientX var downY =e.clientY document.onmousemove=function(e){ console.log(e); // if(div.offsetLeft<1){ // alert("超出") // } //獲取盒子點擊的地方距離document點擊的坐標的差 var moveX =e.clientX - downX var moveY =e.clientY - downY //獲取移動鼠標想放哪放哪 // div.style.left =divX+moveX+"px" // div.style.top =divY+moveY+"px" //這個的中心點在中間 div.style.left =e.clientX - div.offsetWidth/2+"px" div.style.top =e.clientY - div.offsetHeight/2+"px" //拿他們的寬高去判斷坐標 if(e.clientX<div1.offsetWidth+div.offsetWidth/2+200&&e.clientX>div1.offsetWidth+div.offsetWidth/2&&e.clientY>div1.offsetTop/2&&e.clientY<div1.offsetTop*2+40){ console.log(div1.offsetTop); div1.style.backgroundColor="green" }else{ div1.style.backgroundColor="pink" } //拿他們的距離去判斷 if(e.clientX<div2.offsetWidth+div.offsetWidth/2+200&&e.clientX>div1.offsetWidth+div.offsetWidth/2&&e.clientY>div2.offsetTop-div.offsetHeight/2&&e.clientY<div2.offsetTop+div.offsetHeight+div.offsetHeight/2){ div2.style.backgroundColor="blue" }else { div2.style.backgroundColor="orange" } } } //如果按起就不動 div.onmouseup = function(){ document.onmousemove = null } </script> </html>
效果圖:
到此這篇關于讓你的網(wǎng)頁動起來:Javascript+CSS拖曳盒子指南的文章就介紹到這了,更多相關 Javascript+CSS拖曳盒子內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!