我有一个可拖动的div
,只要我不通过top, right, …
CSS改变它的位置就可以正常工作。我的目标是将div的预拖动位置设置为其窗口的右上角,我用top = 0, right = 0
完成;问题是,div
在拖动时坚持到那个位置和stretches。
dragElement(document.getElementById("myModal"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;}
else {elmnt.onmousedown = dragMouseDown;}
function dragMouseDown(w) {
w = w || window.event;
w.preventDefault();
pos3 = w.clientX;
pos4 = w.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;}
function elementDrag(w) {
w = w || window.event;
w.preventDefault();
pos1 = pos3 - w.clientX;
pos2 = pos4 - w.clientY;
pos3 = w.clientX;
pos4 = w.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;}}
#myModal {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
top: 0;
right: 0;}
#myModalheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;}
<div id="myModal">
<div id="myModalheader">Click here to move</div>
<p>Move</p><p>this</p><p>DIV</p>
</div>
任何解决方法?感谢帮助。
给元素一个宽度和高度你应该是好的。
dragElement(document.getElementById("myModal"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;}
else {elmnt.onmousedown = dragMouseDown;}
function dragMouseDown(w) {
w = w || window.event;
w.preventDefault();
pos3 = w.clientX;
pos4 = w.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;}
function elementDrag(w) {
w = w || window.event;
w.preventDefault();
pos1 = pos3 - w.clientX;
pos2 = pos4 - w.clientY;
pos3 = w.clientX;
pos4 = w.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;}}
#myModal {
position: absolute;
z-index: 9; height: 200px; width: 200px;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
top: 0;
right: 0;}
#myModalheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;}
<div id="myModal">
<div id="myModalheader">Click here to move</div>
<p>Move</p><p>this</p><p>DIV</p>
</div>
您也可以使用弹性框将容器放在右侧。
#parentContainer{
display: flex; justify-content: flex-end
}