使用純ES6的JS 來完成的拖動視窗,廣告視窗,公告視窗等功能。
主要會依靠的 offset 跟 clientX、Y的參數做計算。
內容物放在 contentInput , 要嵌入的htmlElement 放在 app,
//主要的程式碼 let startMove = false; let originalPostionX = null; let originalPostionY = null; let newPostionX = null; let newPostionY = null; const createADWindow = (app, id, startX, startY) => { if (document.getElementById(id)) return; const mainDiv = document.createElement("div"); mainDiv.id = id; mainDiv.style.cssText = `position: absolute; top:${startY}px; left: ${startX}px;`; mainDiv.style.width = document.getElementById("widthInput").value + "px"; mainDiv.style.height = document.getElementById("heightInput").value + "px"; mainDiv.style.backgroundColor = "yellow"; mainDiv.style.cursor = "move"; mainDiv.innerHTML = document.getElementById("contentInput").value; mainDiv.onmousedown = adWindowMouseDown; mainDiv.onmouseup = adWindowMouseUp; mainDiv.onmousemove = adWindowMouseMove; mainDiv.onmouseout = adWindowMouseUp; console.log(mainDiv); app.appendChild(mainDiv); }; const adWindowMouseDown = e => { startMove = true; const adElement = document.getElementById("adWindow"); originalPostionX = e.clientX; originalPostionY = e.clientY; console.log( "originalPostionX", originalPostionX, "originalPostionY", originalPostionY ); }; const adWindowMouseUp = e => { startMove = false; }; const adWindowMouseMove = e => { if (!startMove) return; const adElement = document.getElementById("adWindow"); newPostionX = originalPostionX - e.clientX; newPostionY = originalPostionY - e.clientY; originalPostionX = e.clientX; originalPostionY = e.clientY; adElement.style.left = adElement.offsetLeft - newPostionX + "px"; adElement.style.top = adElement.offsetTop - newPostionY + "px"; };
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記