JavaScript

超轻量级php框架startmvc

纯js实现的积木(div层)拖动功能示例

更新时间:2020-05-25 12:06:01 作者:startmvc
本文实例讲述了纯js实现的积木(div层)拖动功能。分享给大家供大家参考,具体如下:<!DOC

本文实例讲述了纯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按钮,获取积木,获取积木后可以在浏览器内随意拖动生成的积木:

纯js 积木 div层 拖动