Home Web Front-end JS Tutorial Various mouse drag-and-drop effects implemented by JavaScript

Various mouse drag-and-drop effects implemented by JavaScript

May 16, 2016 pm 03:33 PM
javascript

This article mainly introduces various mouse drag-and-drop effects implemented by JavaScript, and involves related techniques for JavaScript to dynamically transform page element attributes in response to mouse events. It has certain reference value. Friends who need it can refer to it. The details are as follows:

This is a JavaScript mouse drag and drop effect code. Through this example, you can learn about the trigger object, set the range limit, specify the container size, lock it horizontally and vertically, and also include acquiring and releasing focus, etc.

A screenshot of the running effect is as follows:

The online demo address is as follows:

http://demo.jb51.net/ js/2015/js-mouse-move-fix-style-codes/

The specific code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>拖放效果</title>
</head>
<body>
<script> 
var isIE = (document.all) ? true : false;
var $ = function (id) {
 return "string" == typeof id ? document.getElementById(id) : id;
};
var Class = {
 create: function() {
  return function() { this.initialize.apply(this, arguments); }
 }
}
var Extend = function(destination, source) {
 for (var property in source) {
  destination[property] = source[property];
 }
}
var Bind = function(object, fun) {
 return function() {
  return fun.apply(object, arguments);
 }
}
var BindAsEventListener = function(object, fun) {
 return function(event) {
  return fun.call(object, (event || window.event));
 }
}
var CurrentStyle = function(element){
 return element.currentStyle || document.defaultView.getComputedStyle(element, null);
}
function addEventHandler(oTarget, sEventType, fnHandler) {
 if (oTarget.addEventListener) {
  oTarget.addEventListener(sEventType, fnHandler, false);
 } else if (oTarget.attachEvent) {
  oTarget.attachEvent("on" + sEventType, fnHandler);
 } else {
  oTarget["on" + sEventType] = fnHandler;
 }
};
function removeEventHandler(oTarget, sEventType, fnHandler) {
 if (oTarget.removeEventListener) {
 oTarget.removeEventListener(sEventType, fnHandler, false);
 } else if (oTarget.detachEvent) {
 oTarget.detachEvent("on" + sEventType, fnHandler);
 } else { 
 oTarget["on" + sEventType] = null;
 }
};
//拖放程序
var Drag = Class.create();
Drag.prototype = {
//拖放对象
 initialize: function(drag, options) {
 this.Drag = $(drag);//拖放对象
 this._x = this._y = 0;//记录鼠标相对拖放对象的位置
 this._marginLeft = this._marginTop = 0;//记录margin
 //事件对象(用于绑定移除事件)
 this._fM = BindAsEventListener(this, this.Move);
 this._fS = Bind(this, this.Stop);
 this.SetOptions(options);
 this.Limit = !!this.options.Limit;
 this.mxLeft = parseInt(this.options.mxLeft);
 this.mxRight = parseInt(this.options.mxRight);
 this.mxTop = parseInt(this.options.mxTop);
 this.mxBottom = parseInt(this.options.mxBottom);
 this.LockX = !!this.options.LockX;
 this.LockY = !!this.options.LockY;
 this.Lock = !!this.options.Lock;
 this.onStart = this.options.onStart;
 this.onMove = this.options.onMove;
 this.onStop = this.options.onStop;
 this._Handle = $(this.options.Handle) || this.Drag;
 this._mxContainer = $(this.options.mxContainer) || null;
 this.Drag.style.position = "absolute";
 //透明
 if(isIE && !!this.options.Transparent){
  //填充拖放对象
  with(this._Handle.appendChild(document.createElement("p")).style){
   width = height = "100%"; backgroundColor = "#fff"; filter = "alpha(opacity:0)";
  }
 }
 //修正范围
 this.Repair();
 addEventHandler(this._Handle, "mousedown", BindAsEventListener(this, this.Start));
 },
 //设置默认属性
 SetOptions: function(options) {
 this.options = {//默认值
  Handle:   "",//设置触发对象(不设置则使用拖放对象)
  Limit:   false,//是否设置范围限制(为true时下面参数有用,可以是负数)
  mxLeft:   0,//左边限制
  mxRight:  9999,//右边限制
  mxTop:   0,//上边限制
  mxBottom:  9999,//下边限制
  mxContainer: "",//指定限制在容器内
  LockX:   false,//是否锁定水平方向拖放
  LockY:   false,//是否锁定垂直方向拖放
  Lock:   false,//是否锁定
  Transparent: false,//是否透明
  onStart:  function(){},//开始移动时执行
  onMove:   function(){},//移动时执行
  onStop:   function(){}//结束移动时执行
 };
 Extend(this.options, options || {});
 },
 //准备拖动
 Start: function(oEvent) {
 if(this.Lock){ return; }
 this.Repair();
 //记录鼠标相对拖放对象的位置
 this._x = oEvent.clientX - this.Drag.offsetLeft;
 this._y = oEvent.clientY - this.Drag.offsetTop;
 //记录margin
 this._marginLeft = parseInt(CurrentStyle(this.Drag).marginLeft) || 0;
 this._marginTop = parseInt(CurrentStyle(this.Drag).marginTop) || 0;
 //mousemove时移动 mouseup时停止
 addEventHandler(document, "mousemove", this._fM);
 addEventHandler(document, "mouseup", this._fS);
 if(isIE){
  //焦点丢失
  addEventHandler(this._Handle, "losecapture", this._fS);
  //设置鼠标捕获
  this._Handle.setCapture();
 }else{
  //焦点丢失
  addEventHandler(window, "blur", this._fS);
  //阻止默认动作
  oEvent.preventDefault();
 };
 //附加程序
 this.onStart();
 },
 //修正范围
 Repair: function() {
 if(this.Limit){
  //修正错误范围参数
  this.mxRight = Math.max(this.mxRight, this.mxLeft + this.Drag.offsetWidth);
  this.mxBottom = Math.max(this.mxBottom, this.mxTop + this.Drag.offsetHeight);
  //如果有容器必须设置position为relative来相对定位,并在获取offset之前设置
  !this._mxContainer || CurrentStyle(this._mxContainer).position == "relative" || (this._mxContainer.style.position = "relative");
 }
 },
 //拖动
 Move: function(oEvent) {
 //判断是否锁定
 if(this.Lock){ this.Stop(); return; };
 //清除选择
 window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
 //设置移动参数
 var iLeft = oEvent.clientX - this._x, iTop = oEvent.clientY - this._y;
 //设置范围限制
 if(this.Limit){
  //设置范围参数
  var mxLeft = this.mxLeft, mxRight = this.mxRight, mxTop = this.mxTop, mxBottom = this.mxBottom;
  //如果设置了容器,再修正范围参数
  if(!!this._mxContainer){
   mxLeft = Math.max(mxLeft, 0);
   mxTop = Math.max(mxTop, 0);
   mxRight = Math.min(mxRight, this._mxContainer.clientWidth);
   mxBottom = Math.min(mxBottom, this._mxContainer.clientHeight);
  };
  //修正移动参数
  iLeft = Math.max(Math.min(iLeft, mxRight - this.Drag.offsetWidth), mxLeft);
  iTop = Math.max(Math.min(iTop, mxBottom - this.Drag.offsetHeight), mxTop);
 }
 //设置位置,并修正margin
 if(!this.LockX){ this.Drag.style.left = iLeft - this._marginLeft + "px"; }
 if(!this.LockY){ this.Drag.style.top = iTop - this._marginTop + "px"; }
 //附加程序
 this.onMove();
 },
 //停止拖动
 Stop: function() {
 //移除事件
 removeEventHandler(document, "mousemove", this._fM);
 removeEventHandler(document, "mouseup", this._fS);
 if(isIE){
  removeEventHandler(this._Handle, "losecapture", this._fS);
  this._Handle.releaseCapture();
 }else{
  removeEventHandler(window, "blur", this._fS);
 };
 //附加程序
 this.onStop();
 }
};
</script>
<style> 
#idContainer{ border:10px solid #990000; width:600px; height:300px;}
#idDrag{ border:5px solid #C4E3FD; background:#C4E3FD; width:50px; height:50px; top:50px; left:50px;}
#idHandle{cursor:move; height:25px; background:#0000FF; overflow:hidden;}
</style>
<p id="idContainer">
<p id="idDrag"><p id="idHandle"></p></p>
</p>
<input id="idReset" type="button" value="复位" />
<input id="idLock" type="button" value="锁定" />
<input id="idLockX" type="button" value="锁定水平" />
<input id="idLockY" type="button" value="锁定垂直" />
<input id="idLimit" type="button" value="范围锁定" />
<input id="idLimitOff" type="button" value="取消范围锁定" />
<br />拖放状态:<span id="idShow">未开始</span>
<script> 
var drag = new Drag("idDrag", { mxContainer: "idContainer", Handle: "idHandle", Limit: true,
 onStart: function(){ $("idShow").innerHTML = "开始拖放"; },
 onMove: function(){ $("idShow").innerHTML = "left:"+this.Drag.offsetLeft+";top:"+this.Drag.offsetTop; },
 onStop: function(){ $("idShow").innerHTML = "结束拖放"; }
});
$("idReset").onclick = function(){
 drag.Limit = true;
 drag.mxLeft = drag.mxTop = 0;
 drag.mxRight = drag.mxBottom = 9999;
 drag.LockX = drag.LockY = drag.Lock = false;
}
$("idLock").onclick = function(){ drag.Lock = true; }
$("idLockX").onclick = function(){ drag.LockX = true; }
$("idLockY").onclick = function(){ drag.LockY = true; }
$("idLimit").onclick = function(){  drag.mxRight = drag.mxBottom = 200;drag.Limit = true; }
$("idLimitOff").onclick = function(){ drag.Limit = false; }
</script>
</body>
</html>
Copy after login

The above is the entire content of this chapter. For more related tutorials, please Visit JavaScript Video Tutorial!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles