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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

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),
