單擊影像后,我設定了一個 div 元素。div 也是可拖動的,一旦它出現并且所有功能都很好。但是,當我單擊影像時,div 總是出現在頁面的最左下角,我怎樣才能將它的起始位置更改為頁面的中心,而不會完全弄亂我的作業 JS?希望我缺少一個簡單的 CSS 位置修復 - 我對 html/css/js 比較陌生。
HTML:
<div>
<a href="#/" class="toggler"
><img class="arrow-img" src="images/arrow-in-intro.svg" alt="arrow"
/></a>
</div>
<!-- Draggable DIV -->
<div class="mydiv" id="mydiv">
<div id="mydivheader">System Message</div>
<p>Critical Error</p>
<button onclick="window.location.href='/main.html'">Ok</button>
</div>
CSS:
#mydiv {
position: absolute;
z-index: 999;
background-color: #afafaf;
border: 2px solid #8c8c8c;
text-align: center;
font-family: "Courier New", Courier, monospace;
font-weight: 400;
width: 200px;
}
#mydivheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #0000a4;
color: rgb(255, 255, 255);
}
.mydiv {
opacity: 0;
}
.mydiv.show {
opacity: 1;
}
JS:
<script>
var elementToClick = document.querySelector(".toggler");
var elementToShow = document.querySelector(".mydiv");
if (elementToClick) {
elementToClick.addEventListener("click", showElement);
}
function showElement() {
elementToShow.classList.add("show");
}
</script>
<script>
// Make the DIV element draggable:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
var pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
if (document.getElementById(elmnt.id "header")) {
// if present, the header is where you move the DIV from:
document.getElementById(elmnt.id "header").onmousedown =
dragMouseDown;
} else {
// otherwise, move the DIV from anywhere inside the DIV:
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = elmnt.offsetTop - pos2 "px";
elmnt.style.left = elmnt.offsetLeft - pos1 "px";
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}
</script>
uj5u.com熱心網友回復:
你可以添加top: 50%; left: 50%;到#mydiv
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478977.html
標籤:javascript html jQuery css
