用js控制div跟随鼠标移动,鼠标点击后,鼠标离开,div留在当前点击的位置怎么做

2024-11-22 13:25:44
推荐回答(2个)
回答1:

var drag_ = false
var D = new Function('obj', 'return document.getElementById(obj);')
var oevent = new Function('e', 'if (!e) e = window.event;return e')
function Move_obj(obj) {
var x, y;
D(obj).onmousedown = function (e) {
drag_ = true;
with (this) {
style.position = "absolute"; var temp1 = offsetLeft; var temp2 = offsetTop;
x = oevent(e).clientX; y = oevent(e).clientY;
document.onmousemove = function (e) {
if (!drag_) return false;
with (this) {
style.left = temp1 + oevent(e).clientX - x + "px";
style.top = temp2 + oevent(e).clientY - y + "px";
}
}
}
document.onmouseup = new Function("drag_=false");
}
}



如果需要以后都留在此位置,需把当前位置的坐标保存到数据库,下次打开时读取数据加载div

回答2:







#box{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
}


window.onload = function(){

var box = document.getElementById("box");

var move = function(event){
var x = event.pageX;
var y = event.pageY;

box.style.left = x - 0.5*box.offsetWidth + "px";
box.style.top = y - 0.5*box.offsetHeight + "px";

}

box.onclick = function(){
document.onmousemove = null;
}

box.ondblclick = function(){
document.onmousemove = move;
}

document.onmousemove = move;
}





相关问答