js实现拖拽功能
更新时间:2017年03月01日 10:39:29 作者:13751343826
本文主要介绍了js实现拖拽效果的实例,具有很好的参考价值,下面跟着小编一起来看下吧
效果图:(红色方块可任意拖动)

代码如下:
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
body{
background:url("img/2345_image_file_copy_1.jpg");
}
#d1{
width:100px;
height:100px;
background:red;
margin-left:300px;
}
</style>
</head>
<body>
<div id="d1"></div>
</body>
<script>
window.onload=function(){
var d1=document.getElementById("d1");
d1.onmousedown=function(e){
var mouseX=e.clientX;
var mouseY=e.clientY;//计算xy
var pianyiX=mouseX-d1.offsetLeft;
var pianyiY=mouseY-d1.offsetTop;
document.onmousemove=function(e){
var newX=e.clientX-pianyiX;
var newY=e.clientY-pianyiY;
d1.style.marginLeft=newX+"px";
d1.style.marginTop=newY+"px";
}
};
document.onmouseup = function(e){
document.onmousemove = null ;
};
}
/*
结果,上面的onmousemove要写在document上,我写在div上导致错误
*/
</script>
</html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!
相关文章
cropper.js和exif.js实现头像上传缩放裁剪旋转
这篇文章主要为大家详细介绍了cropper.js和exif.js实现头像上传缩放裁剪旋转,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-02-02
JavaScript.The.Good.Parts阅读笔记(二)作用域&闭包&减缓全局空间污染
块级作用域: 大多数使用c语言语法的语言都有块级作用域,而JavaScript没有块级作用域。2010-11-11


最新评论