用js控制div跟随鼠标移动,鼠标点击后,鼠标离开,div留在当前点击的位置怎么做
2个回答
展开全部
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 onmousedown="Move_obj(this.id)" id="dd" style="width:100px;height:100px;background:red"></div>
如果需要以后都留在此位置,需把当前位置的坐标保存到数据库,下次打开时读取数据加载div
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 onmousedown="Move_obj(this.id)" id="dd" style="width:100px;height:100px;background:red"></div>
如果需要以后都留在此位置,需把当前位置的坐标保存到数据库,下次打开时读取数据加载div
更多追问追答
追问
这是鼠标拖动效果,
我想要的是div跟随鼠标移动,单击后,鼠标离开,div不再跟随移动,div停留在鼠标单击的位置,鼠标可以随意移动
追答
差不多吧,你拖运到你想要的位置之后鼠标放开就行了
展开全部
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
}
</style>
<script type="text/javascript">
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;
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询