Detailed explanation of encapsulating an own module instance

小云云
Release: 2018-01-30 17:16:08
Original
1421 people have browsed it

Try to encapsulate a drag and drop module. I went through some twists and turns in the process. At first, I planned to only use style.left, but this requires setting position: absolute. It may have some impact on the code. Although CSS transform will affect compatibility, here I still use the translate of this attribute to complete the move.

Code completed with style only

Without further ado, let’s go directly to the code:

html and css, position must be set here, this is the first time I write this code I forgot about it at the time, but in the end, even though the JS was written correctly, the effect couldn't come out at all... It was really short-circuited

    学习  
  

Copy after login

Point! ! JS

; //这个分号是为了防止其他的模块最后忘记加分号,导致错误。 (function() { //构造函数,属于每一个实例 function Drag(selector) { this.elem = typeof selector == 'object' ? selector : document.getElementById(selector); //鼠标初始位置 this.startX = 0; this.startY = 0; //元素初始位置 this.sourceX = 0; this.sourceY = 0; this.init(); } //原型,共有的 Drag.prototype = { constructor: Drag, init: function() { this.setDrag(); }, //用于获取元素当前的位置信息 getPosition: function() { var that = this; var pos = {}; pos = { x: that.elem.offsetLeft, y: that.elem.offsetTop }; return pos; }, //用来设置当前元素的位置 setPosition: function(pos) { this.elem.style.left = pos.x + 'px'; this.elem.style.top = pos.y + 'px'; }, //该方法用来绑定事件 setDrag: function() { var self = this; this.elem.addEventListener('mousedown', start, false); function start(event) { self.startX = event.pageX; self.startY = event.pageY; var pos = self.getPosition(); self.sourceX = pos.x; self.sourceY = pos.y; document.addEventListener('mousemove', move, false); document.addEventListener('mouseup', end, false); } function move(event) { //总体思想:鼠标距浏览器距-鼠标距元素距离 var currentX = event.pageX; //当前的鼠标x位置 var currentY = event.pageY; //当前的鼠标y位置 var distanceX = currentX - self.startX; //鼠标移动的距离x var distanceY = currentY - self.startY; //鼠标移动的距离y self.setPosition({ x: self.sourceX + distanceX, y: self.sourceY + distanceY }); } function end(event) { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', end); } } }; //暴露在外 window.Drag = Drag; })(); new Drag('box');
Copy after login

This code is relatively easy to understand. When I first looked at Bo Dashen's code, I actually didn't understand the use of translate very clearly, because I didn't expect why regular expressions were used... ....

Although it is relatively simple, we still need to analyze the principle of this code:

1. There is a constructor Drag() in the self-executing function. The methods and properties we set are unique to each constructor instance, such as their location information. There are three methods in the prototype: getPosition() to obtain element position information, setPosition() to set element position, and setDrag() to bind events. Since these three are public, in order to save resources, we Put it in the prototype.

2. The principle of execution of this code is: when the mouse is pressed, the initial position information of the element sourceX/Y and the initial position information of the mouse startX/Y are obtained; when the mouse movement is completed, the new position of the mouse is obtained. currentX/Y, subtract the two mouse positions to get the distanceX/Y that the mouse moves, which is also the distance the element moves. Then, we assign this value to the element's style.left/top. Dragging of elements is achieved.

The combination of transform and style

Due to the development of technology, more and more devices begin to support CSS3. In addition, style takes up more resources and has problems with efficiency, so we Consider using transform.

Browser compatible writing method

We first add the private attribute before the function Drag():

var transform = getTransform();
Copy after login

Add the private method below:

function getTransform() { var transform = "", pStyle = document.createElement('p').style, transformArr = ['transform', 'webkitTransform', 'MozTransform', 'msTransform', 'oTransform'], i = 0, l = transformArr.length; for (; i < l; i++) { if (transformArr[i] in pStyle) { return transform = transformArr[i]; } } return transform; }
Copy after login

PS: Remember the createElement() method, it will be useful next time when judging browser compatibility!

We also need to add a function under getPosition() in the same form:

getTranslate: function() { var val = {}; var transformValue = document.defaultView.getComputedStyle(this.elem, false)[transform]; if(transformValue=='none'){ val={x:0,y:0}; }else{ var transformArr = transformValue.match(/-?\d+/g); val = { x: Number(transformArr[4]), y: Number(transformArr[5]) }; } return val; },
Copy after login

PS: The reason why we need to determine whether transformValue is none is because in the initialization state, The element has not been set with the transform attribute, so the array after regularization cannot find[4][5], so we set the two attributes of val to 0, which will become the transform later. The values of translateX and translateY.

Continue writing code. In the above paragraph we used to extract the X and Y values of translate. Look at the following paragraph:

getPosition: function() { var that = this; var pos = {}; if(transform){ var val=this.getTranslate(); pos={ x:val.x, y:val.y }; }else{ pos = { x: that.elem.offsetLeft, y: that.elem.offsetTop }; } return pos; },
Copy after login

Pay attention to the content we modified in the above code. Here we add a judgment: when a browser that supports the transform attribute exists, we will use the transform attribute to modify the value of the element. Assign the x and y previously obtained in getTranslate to the x and y of pos.

In the above code, we will use different methods to get the same value according to the browser. The value of val comes from getTranslate(), which we extract from the transform of the element. Similarly, in setPosition() below, we also need to set the if judgment.

setPosition: function(pos) { if (transform) { this.elem.style[transform] = 'translate(' + pos.x + 'px' + ',' + pos.y + 'px)'; } else { this.elem.style.left = pos.x + 'px'; this.elem.style.top = pos.y + 'px'; } },
Copy after login

There is nothing to talk about in this paragraph, it is just assigning values in different forms.

At this point, the module is encapsulated. Next, let’s take a look at the complete code:

; (function() { //私有属性 var transform = getTransform(); //构造函数,属于每一个实例 function Drag(selector) { this.elem = typeof selector == 'object' ? selector : document.getElementById(selector); //鼠标初始位置 this.startX = 0; this.startY = 0; //元素初始位置 this.sourceX = 0; this.sourceY = 0; this.init(); } //原型,共有的 Drag.prototype = { constructor: Drag, init: function() { this.setDrag(); }, //用于获取元素当前的位置信息 getPosition: function() { var that = this; var pos = {}; if(transform){ var val=this.getTranslate(); pos={ x:val.x, y:val.y }; }else{ pos = { x: that.elem.offsetLeft, y: that.elem.offsetTop }; } return pos; }, //获取translate值 getTranslate: function() { var val = {}; var transformValue = document.defaultView.getComputedStyle(this.elem, false)[transform]; if(transformValue=='none'){ val={x:0,y:0}; }else{ var transformArr = transformValue.match(/-?\d+/g); val = { x: Number(transformArr[4]), y: Number(transformArr[5]) }; } return val; }, //用来设置当前元素的位置 setPosition: function(pos) { if (transform) { this.elem.style[transform] = 'translate(' + pos.x + 'px' + ',' + pos.y + 'px)'; } else { this.elem.style.left = pos.x + 'px'; this.elem.style.top = pos.y + 'px'; } }, //该方法用来绑定事件 setDrag: function() { var self = this; this.elem.addEventListener('mousedown', start, false); function start(event) { self.startX = event.pageX; self.startY = event.pageY; var pos = self.getPosition(); self.sourceX = pos.x; self.sourceY = pos.y; document.addEventListener('mousemove', move, false); document.addEventListener('mouseup', end, false); } function move(event) { //总体思想:鼠标距浏览器距-鼠标距元素距离 var currentX = event.pageX; //当前的鼠标x位置 var currentY = event.pageY; //当前的鼠标y位置 var distanceX = currentX - self.startX; //鼠标移动的距离x var distanceY = currentY - self.startY; //鼠标移动的距离y self.setPosition({ x: self.sourceX + distanceX, y: self.sourceY + distanceY }); } function end(event) { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', end); } } }; //私有方法,用来获取transform的兼容写法 function getTransform() { var transform = "", pStyle = document.createElement('p').style, transformArr = ['transform', 'webkitTransform', 'MozTransform', 'msTransform', 'oTransform'], i = 0, l = transformArr.length; for (; i < l; i++) { if (transformArr[i] in pStyle) { return transform = transformArr[i]; } } return transform; } //暴露在外 window.Drag = Drag; })(); new Drag('box');
Copy after login

Related recommendations:

javascript global variable encapsulation module implementation code_javascript skills

The above is the detailed content of Detailed explanation of encapsulating an own module instance. 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!