Home > Web Front-end > JS Tutorial > body text

An example of how to implement the building block drag function using pure JavaScript

黄舟
Release: 2017-07-20 17:04:51
Original
1555 people have browsed it

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 = &#39;<p id="s&#39;+num+&#39;"style="width: 200px;height: 200px;position: absolute;background:rgb(&#39;+num1+&#39;,&#39;+num2+&#39;,&#39;+num3+&#39;)"></p>&#39;
    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+&#39;px&#39;;
        obj.style.top = even.pageY-objy+&#39;px&#39;;
      };
      document.onmouseup = function(){
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };
    return false;
  }
</script>
<html>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template