js實(shí)現(xiàn)簡單圖片拖拽效果
本文實(shí)例為大家分享了js實(shí)現(xiàn)簡單圖片拖拽效果的具體代碼,供大家參考,具體內(nèi)容如下
//圖片需要自己導(dǎo)入<!doctype html><html> <head> <meta charset='UTF-8'> <title>在當(dāng)前顯示區(qū)范圍內(nèi)實(shí)現(xiàn)點(diǎn)不到的小方塊</title> <style> div{position:fixed;width:100px;height:100px; background-image:url(images/xiaoxin.gif); background-size:100%; } </style> </head> <body> <div id='pop'></div> <script> let pop = document.getElementById('pop') //定義開關(guān)變量,用于控制圖片是否跟隨鼠標(biāo)移動 let canMove = false; //在開始拖拽時,就保存鼠標(biāo)距div左上角的相對位置 let offsetX,offsetY; //當(dāng)在pop上按下鼠標(biāo)時 pop.onmousedown=function(e){ //可以開始拖動 canMove=true; offsetX=e.offsetX; offsetY=e.offsetY; } //當(dāng)鼠標(biāo)在窗口移動時 window.onmousemove=function(e){ //只有當(dāng)pop可以移動時 if(canMove==true){ //讓pop跟隨鼠標(biāo)移動 //開始拖拽時,立刻獲得鼠標(biāo)距圖片左上角的相對位置 //求pop的top和left let left=e.clientX-offsetX; let top=e.clientY-offsetY; //設(shè)置pop的top和left屬性 pop.style.left=left+'px'; pop.style.top=top+'px'; } } //當(dāng)在pop上抬起鼠標(biāo)按鍵時 pop.onmouseup=function(){ //停止拖拽 canMove=false } </script> </body></html>
效果圖:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
