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