Home  >  Article  >  Web Front-end  >  JavaScript code display to implement image dragging effect

JavaScript code display to implement image dragging effect

巴扎黑
巴扎黑Original
2017-09-09 10:04:461460browse

This article mainly introduces JavaScript to realize the image dragging effect in detail. It has certain reference value. Interested friends can refer to it.

The example in this article shares with you the js to realize the image dragging effect. The specific code is for your reference. The specific content is as follows


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <style>
  #pbox{
   width: 100%;
   height:100%;
  }
  #box{
   width: 200px;
   height: 200px;
   background:red;
   position: absolute;
  }
 </style>
</head>
<body>
<input type="button" id="btn" value="随机生成">
<p id="pbox">
<p id="box">

</p>
</p>
</body>
<script>
 var btn=document.getElementById("btn");//获取按钮
 var box=document.getElementById("box");//获取box
 var pbox=document.getElementById("pbox");//获取pbox
 var arr=[&#39;#fff143&#39;,&#39;#ff7500&#39;,&#39;#a3d900&#39;,&#39;#eedeb0&#39;,&#39;#ae7000&#39;,&#39;#b35c44&#39;,&#39;#392f41&#39;,&#39;#ff461f&#39;,&#39;#44cef6&#39;,&#39;#edd1db&#39;,&#39;#003371&#39;];//随机颜色
 //给btn注册点击事件ain
 btn.onclick=function(){
   pbox.innerHTML="";//清空pbo
  for(var i=0;i<=10;i++){
   var newTip =box.cloneNode(true);
   pbox.appendChild(newTip);
   var left=parseInt(Math.random()*(900-100+1) + 100);//随机生成左边距
   var top=parseInt(Math.random()*(500-100+1) + 100);//随机生成上边距
   var bg=Math.floor((Math.random()*arr.length));//生成数组随机数获得随机数组下标
   box.style.background=arr[bg];//设置颜色
   box.style.top=top+"px";//设置上边距
   box.style.left=left+"px";//设置左边距

  }
  var c=pbox.children;

  for(var i=0;i< c.length;i++){
   c[i].onmousedown=function (e) {
//     alert(this.offsetLeft);
    var spacex=e.pageX-this.offsetLeft;
    var spacey=e.pageY-this.offsetTop;
    this.onmousemove=function (e) {
     this.style.left=e.pageX-spacex+"px";
     this.style.top=e.pageY-spacey+"px";
    }
   };
   c[i].onmouseup=function () {
    this.onmousemove=null;
   }
  }
 }
</script>
</html>

The above is the detailed content of JavaScript code display to implement image dragging effect. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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