原生:点击创建div,且能够拖动
css、html
<style type="text/css"> .active{ width: 100px; height: 100px; position: absolute; } </style> <body> <input type="button" value="创建div" id="oBtn" /> </body>
js
<script src="public.js"></script> <script> var btn = document.getElementById("oBtn"); btn.onclick = function(){ new DragDiv().init() } function DragDiv(){ this.div = document.createElement("div"); this.init = function(){ document.body.appendChild(this.div); this.div.className = "active"; this.div.style.left = rand(0,window.innerWidth - 100) + "px"; this.div.style.top = rand(0,window.innerHeight - 100) + "px"; this.div.style.background = getColor(); this.drag(); } this.drag = function(){ //这里的this还是实例 this.div.onmousedown = function(e){ e = e || event; this.down(e); document.onmousemove = function(e){ e = e || event; this.move(e); }.bind(this) document.onmouseup = function(){ this.up(); }.bind(this); return false; }.bind(this) } this.down = function(e){ this.disX = e.offsetX; this.disY = e.offsetY; } this.move= function(e){ this.div.style.left = e.pageX - this.disX + "px"; this.div.style.top = e.pageY - this.disY + "px"; } this.up = function(){ document.onmousemove = null; } } </script>
public.js
function $id(id){//给我一个id名,返回一个这个id的元素 return document.getElementById(id); } //求随机数 function rand(min,max){ return Math.round(Math.random()*(max - min) + min); } //随机的16进制颜色 function getColor(){ var str = "0123456789ABCDEF";//十六进制字符串 var color = "#"; for(var i = 0; i <= 5; i++){//取6个数 color += str.charAt(rand(0,15)); //rand(0,15)随机0-15之间的数,作为charAt()的下标,取出下标对应的字符 } return color; } function zero(val){ return val < 10 ? "0" + val : val; } //时间差 function diff(start,end){//2000-2018 2018 - 2000 //console.log(start.getTime()); return Math.abs(start.getTime() - end.getTime())/1000; }