javascript怎么实现鼠标点击一张图片之后,图片跟随鼠标走的效果

JavaScript05

javascript怎么实现鼠标点击一张图片之后,图片跟随鼠标走的效果,第1张

这是一个拖动元素的效果

<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>

我运行了你的代码,其实是可以复制粘贴的,因为你设置的复制出的图像覆盖了原来的位置了,这个可以查看元素可以看得到的。你可以改变

if(Obj!=null)

{

Obj.style.left = event.x-Obj.l

Obj.style.top = event.y-Obj.t

}

改成

if(Obj!=null)

{

Obj.style.left = event.x-Obj.l+100+'px'

Obj.style.top = event.y-Obj.t+100+'px'

}

就可以看得出来了

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=UTF-8">

<title>Document</title>

</head>

<body>

<div id="box1" style = 'width:100pxheight: 100pxbackground:#cccposition:fixed'></div>

<!-- 注意 盒子一定要定位 position:fixed或者 position:absolute-->

</body>

<script type="text/javascript">

function getPos(e){//这是一个 获取鼠标位置的函数

var oEvent = e || event

return {x: oEvent.clientX + document.documentElement.scrollLeft || document.body.scrollLeft,

y: oEvent.clientY +document.documentElement.scrollTop || document.body.scrollTop}

}

document.getElementById('box1').onmousedown = function(e){ //你要拖动对象在mousedown的时候发生的事情

var oEvent = e || event

var pos = getPos(oEvent)

var _this = this

_this.style.cursor = 'move'//改变鼠标状态

_this.disY = pos.y - _this.offsetTop

_this.disX = pos.x - _this.offsetLeft

document.onmousemove =function(e){ //在鼠标按下的时候 并且 移动的时候 发生的事情

var oEvent = e || event

var dpos = getPos(oEvent)

var t = dpos.y-_this.disY //移动的时候获取的 移动 top值

var l = dpos.x-_this.disX //移动的时候获取的 移动 left

_this.style.top=t + "px" //这两条给盒子赋值

_this.style.left=l + "px"

}

document.onmouseup = function(){//鼠标弹起的时候做的事情 一些释放 操作

_this.style.cursor = 'pointer'

this.onmousemove = null

this.onmouseup = null

try{

_this.releaseCapture()}catch(e){}

}

try{

_this.setCapture()}catch(b){} //这里是为了 让盒子拖动的时候不要复制页面里面的其他内容

return false

}

</script>

</html>