Detailed explanation of encapsulating an own module instance
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
nbsp;html> <meta> <title>学习</title> <style> *{ margin: 0; padding: 0; } #box{ width: 200px; height: 200px; background: #6f6; font-size: 20px; cursor:move; position: absolute; } </style> <p></p> <script></script>
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');
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();
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 <h4 id="PS-Remember-the-createElement-method-it-will-be-useful-next-time-when-judging-browser-compatibility">PS: Remember the createElement() method, it will be useful next time when judging browser compatibility! </h4><p>We also need to add a function under getPosition() in the same form: </p><pre class="brush:php;toolbar:false">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; },
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; },
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'; } },
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 <p> Related recommendations: <br></p><p><a href="http://www.php.cn/js-tutorial-18434.html" target="_self">javascript global variable encapsulation module implementation code_javascript skills</a></p>
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!

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment