This article mainly introduces the building block (p layer) dragging function implemented in pure js, and analyzes the related operation skills of javascript randomly generating p layers of various colors and responding to mouse events to change element attributes to achieve dragging effects in the form of examples. , Friends who need it can refer to
The example in this article describes the building block (p layer) drag function implemented in pure js. Share it with everyone for your reference, the details are as follows:
<!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="p3"/> </body> <script> //生成积木 document.getElementById("p3").onclick=function(){ var num = getnumber(); var num1 = getnumber(); var num2 = getnumber(); var num3 = getnumber(); var ps = '<p id="s'+num+'"style="width: 200px;height: 200px;position: absolute;background:rgb('+num1+','+num2+','+num3+')"></p>' document.getElementById("content").insertAdjacentHTML("beforeEnd",ps); 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){ //鼠标到p的距离 objx = even.clientX - obj.offsetLeft; objy = even.clientY - obj.offsetTop; //p移动的距离 = 鼠标到父窗口的距离 - 鼠标到p的距离 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>
Click the button button to obtain the building blocks. After obtaining the building blocks, you can drag the generated building blocks at will in the browser:
The above is the detailed content of An example of how to implement the building block drag function using pure JavaScript. For more information, please follow other related articles on the PHP Chinese website!