欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

js解决movebox移动问题_javascript技巧

程序员文章站 2022-04-01 14:54:01
...
本文为大家分享了js解决movebox移动问题,并且取消图片默认拖动事件的相关操作,供大家参考,具体内容如下

html:

 
 
 
js解决movebox移动问题_javascript技巧
js解决movebox移动问题_javascript技巧

js:

var movebox; 
window.onload = function () { 
  movebox = document.getElementById("movebox"); 
  movebox.addEventListener("mousedown", function (e) { 
    if (e.button > 0) { 
      fun2(); 
      return false; 
    } 
    e.preventDefault && e.preventDefault(); //明哥:去掉图片拖动响应 狠重要 
    gen.x = e.clientX; 
    gen.y = e.clientY; 
    gen._x = movebox.offsetLeft; 
    gen._y = movebox.offsetTop; 
    gen.dx = gen.x - gen._x; 
    gen.dy = gen.y - gen._y; 
    document.addEventListener("mousemove",fun1,false); 
    document.addEventListener("mouseup", fun2, false); 
  }, false); 
}; 
var fun1 = function (e) { 
  gen.L = e.clientX - gen.dx; 
  gen.T = e.clientY - gen.dy; 
  var timefun = function () { 
    window.getSelection().removeAllRanges(); 
    if (gen.L  200) 
      gen.L = 200; 
    if (gen.T  175) 
      gen.T = 175; 
    setLT(movebox, gen.L, gen.T); 
  }; 
  setTimeout(timefun, 2); 
}; 
var fun2 = function () { 
  document.removeEventListener("mousemove", fun1, false); 
  document.removeEventListener("mouseuo", fun2, false); 
}; 
var gen = { 
  x: null, 
  y: null, 
  _x: null, 
  _y: null, 
  dx: null, 
  dy: null, 
  L: null, 
  T:null, 
}; 
var setLT = function (dom, L, T) { 
  dom.style.left = L + "px"; 
  dom.style.top = T + "px"; 
}; 

css:

body { 
  position:absolute; 
  margin:0; 
  padding:0; 
} 
#center{ 
  position:absolute; 
  top:200px; 
  left:300px; 
  width:400px; 
  height:400px; 
  background-color:#808080; 
} 
#black{ 
  position:absolute; 
  width:400px; 
  height:400px; 
  z-index:80; 
  background-color:#000; 
  opacity:0.6; 
} 
#bigimg{ 
  z-index:50; 
  position:absolute; 
  left:100px; 
  top:125px; 
} 
#movebox{ 
  z-index:100; 
  position:absolute; 
  width:100px; 
  height:100px; 
  left:150px; 
  top:150px; 
  overflow:hidden; 
  cursor:move; 
  background-color:#ff6a00; 
} 
#moveimg{ 
  position:absolute; 
  left:-50px; 
  top:-25px; 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助。

相关标签: js movebox 移动