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

JavaScript013

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

你要的应该是拖拽效果,可以通过jq插件做

http://www.runoob.com/jqueryui/example-draggable.html

基本原理就是鼠标按下修改div的left和top(或者right/bottom)。鼠标离开不变。

<!DOCTYPE html>

<html>

<head>

<script src="/jquery/jquery-1.11.1.min.js">

</script>

<Style>

#test{

position:absolute

}

</style>

<script>

$(document).mousedown(function(){

       $(this).mousemove(function(e){

$("#test").css({ "left": e.pageX+"px", "top": e.pageY+"px" }) 

           $(document).mouseup(function(){

               $(this).unbind('mousemove')

           })

       })

   })

</script>

</head>

<body>

<div id="test">ssssssssss</div>

</body>

</html>

(若有事件,事件触发时)获取鼠标的x、y坐标值,在把坐标值赋值给元素的定位值

获取鼠标的坐标值方式有多种,event.client/screen/page/offset,自己去了解对比下用法和区别

这是一个拖动元素的效果

<div id="div" style="width:100pxheight:100pxbackground-color:redposition: absolutecursor: move">

</div>

<script>

window.onload=function(){

var div=document.getElementById("div")

div.onmousedown=function(e){ //把onmousedown改成onclick就是你要的效果

var x= e.clientX-div.offsetLeft

var y= e.clientY-div.offsetTop

document.onmousemove=function(e){

div.style.left= e.clientX-x+"px"

div.style.top= e.clientY-y+"px"

}

document.onmouseup=function(){

document.onmousemove=null

}

}

}

</script>