我正在学习JavaScript。有一段代码可以移动块,但我无法将其保存在localStorage中。求助!
let drag = document.querySelector('.note');
drag.onmousedown = function(e) {
let coord = getCoord(drag);
let shiftX = e.pageX - coord.left;
let shiftY = e.pageY - coord.top;
drag.style.position = 'absolute';
document.body.appendChild(drag);
moveNote(e);
drag.style.zIndex = 1000;
function moveNote(e) {
drag.style.left = e.pageX - shiftX + 'px';
drag.style.top = e.pageY - shiftY + 'px';
}
document.onmousemove = function(e) {
moveNote(e);
};
drag.onmouseup = function() {
document.onmousemove = null;
drag.onmouseup = null;
};
}
function getCoord(elem) {
let main = elem.getBoundingClientRect();
return {
top: main.top,
left: main.left
};
}
.note {
width: 50px;
height: 50px;
background: red;
}
<div class="note">
</div>