纯js实现的积木(div层)拖动功能示例
本文实例讲述了纯js实现的积木(div层)拖动功能。分享给大家供大家参考,具体如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖动</title> <style type="text/css"> </style> </head> <body id="content"> <input type="button" value="获取积木" id="div3"/> </body> <script> //生成积木 document.getElementById("div3").onclick=function(){ var num = getnumber(); var num1 = getnumber(); var num2 = getnumber(); var num3 = getnumber(); var divs = '<div id="s'+num+'"style="width: 200px;height: 200px;position: absolute;background:rgb('+num1+','+num2+','+num3+')"></div>' document.getElementById("content").insertAdjacentHTML("beforeEnd",divs); darg1("s"+num+""); }; //h获取随机数,获取随机颜色 function getnumber(){ return parseInt(Math.random()*255); } //拖动积木 function darg1(id){ var obj = document.getElementById(id); var objx = 0; var objy = 0; obj.onmousedown = function(even){ //鼠标到div的距离 objx = even.clientX - obj.offsetLeft; objy = even.clientY - obj.offsetTop; //div移动的距离 = 鼠标到父窗口的距离 - 鼠标到div的距离 document.onmousemove = function(even){ obj.style.left = even.pageX-objx+'px'; obj.style.top = even.pageY-objy+'px'; }; document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; }; }; return false; } </script> <html>
点击button按钮,获取积木,获取积木后可以在浏览器内随意拖动生成的积木:
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数据结构与算法技巧总结》、《JavaScript数学运算用法总结》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》及《JavaScript遍历算法与技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。
相关推荐
阿斌Elements 2020-06-11
zrtlin 2020-11-09
xuebingnan 2020-11-05
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
softwear 2020-08-21
ZGCdemo 2020-08-16
jczwilliam 2020-08-16
littleFatty 2020-08-16
idning 2020-08-03
jinxiutong 2020-07-26
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25
Aveiox 2020-06-23