directory
- Copy the object.create () function in ECMAScript5
- Trim () emulates the string.trim () function in ECMAScript5
- Copy the array.reduce () function in ECMAScript5
- Copy ECMAScript5’s object.keys () function
- Bind () in ECMAScript5
- Copy the array.map () function in ECMAScript5
- Mimicking the math.max () method
- Copy the string.match () method
- Imitation HTML5 classList attribute implementation
- Mock the function. name property implementation
- Returns the NTH ancestor element of the element
- Returns the NTH sibling of the element
- Returns the NTH child of the element
- Native JS makes CSS animation vibrate
- Native JS implements CSS animation hiding
- Finds all occurrences of elements in an array
- Special treatment for special cases of data type detection
- Implement the outerHTML property with innerHTML
- Insert the node
- List the child nodes in reverse order
- Query the position of the window scroll bar
- Query the viewport size of a window
- Row sorting of a table
- Generate table of contents
- Array to heavy
- Bubble sort
- Parse the parameters from the URL
- Gets the element content of plain text
- Hand write a JSONP implementation
- Query content in plain text
- Find all Text nodes in nodes that are descendants of the element
- Use innerHTML to implement insertAdjacentHTML
- Drag and drop
Copy the object.create () function in ECMAScript5
function inherit(obj) { if (obj === null) throw TypeError(); if (Object.create) return Object.create(obj); var t = typeof obj; if (t ! == "object" && t ! == "function") throw TypeError(); function Fn() {}; Fn.prototype = obj; return new Fn(); }Copy the code
Trim () emulates the string.trim () function in ECMAScript5
String.prototype.mytrim = function () { String.prototype.trim || function () { if (! this) return this; / / handle return an empty string is not do this. The replace (/ ^ \ s + | \ s + $/ g, "") / / use regular expressions in Spaces replaced}}Copy the code
Copy the array.reduce () function in ECMAScript5
var reduce = Array.prototype.reduce ? Function (ary, fn, initial) {if (arguments.length > 2) {return ary.reduce(fn, initial); // If an initial value is passed in} else {return ary.reduce(fn); }} : function (ary, fn, initial) {var I = 0, len = ary.length, accumulator; if (arguments.length > 2) { accumulator = initial; If (len == 0) throw TypeError(); while (i < len) { if (i in ary) { accumulator = ary[i++]; break; } else { i++; } } if (i == len) throw TypeError(); } while (I < len) {/ / for the rest of the elements in the array, in turn, invoke fn the if (I in ary) {accumulator = fn. Call (undefined, accumulator, ary [I], I, ary) } i++; } return accumulator; }Copy the code
Finds all occurrences of elements in an array
function findAll(ary, ele) {
var results = [],
len = a.length,
pos = 0;
while (pos < len) {
pos = ary.indexOf(ele, pos);
if (pos === -1) break;
results.push(pos);
pos++;
}
return results;
}Copy the code
Data type detection, special processing in special cases
function classOf(obj) {
if (obj === null) return "Null";
if (obj === undefined) return 'Undefined';
return Object.prototype.toString.call(obj).slice(8, -1);
}Copy the code
Copy ECMAScript5’s object.keys () function
function keys(obj) { if (typeof obj ! == "object") { throw TypeError(); } var result = []; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { result.push(prop); } } return result; }Copy the code
Imitation of math.max method (Indefinite argument function)
function max() {
var max = Number.NEGATIVE_INFINITY;
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] > max) max = arguments[i];
}
return max;
}Copy the code
Bind () in ECMAScript5
if (! Function.prototype.bind) { Function.prototype.bind = function (obj) { var self = this, boundArgs = arguments; return function () { var args = [], i; for (i = 1; i < boundArgs.length; i++) args.push(boundArgs[i]); for (i = 1; i < arguments.length; i++) args.push(arguments[i]); return self.apply(obj, args); }}}Copy the code
Copy the array.map () function in ECMAScript5
var map = Array.prototype.map ? function (ary, fn) {
return ary.map(fn);
} : function (ary, fn) {
var results = [];
for (var i = 0, len = ary.length; i < len; i++) {
if (i in ary) {
results[i] = fn.call(null, ary[i], i, ary);
}
}
return results;
}Copy the code
Array to heavy
Array.prototype.unique = function unique() {
var obj = {};
for (var i = 0; i < this.length; i++) {
var current = this[i];
if (obj[current] === current) {
current = this[this.length - 1];
this.length--;
i--;
continue;
}
obj[current] = current
}
obj = null;
return this;
}Copy the code
Bubble sort
Array.prototype.bubbleSort = function bubbleSort() {
var temp = null;
for (var i = 0; i < this.length - 1; i++) {
for (var k = 0; k < this.length - 1 - i; k++) {
if (this[k] > this[k + 1]) {
temp = this[k];
this[k] = this[k + 1];
this[k + 1] = temp;
}
}
}
return this;
}
Copy the code
Copy the string.match () method
String.prototype.mymatch = function (reg) {
var ary = [];
var res = reg.exec(this);
while (res) {
ary.push(res[0]);
res = reg.exec(this);
}
return ary;
}Copy the code
Returns the NTH ancestor element of the element
/** * Returns the NTH ancestor of Element ele, or null if no such ancestor exists or if the ancestor is not Element. * (Document or DocumentFragment, for example) returns e if n is 0. Function parent(ele, n) {if (n === defined) n = 1; function parent(ele, n) {if (n === defined) n = 1; while (n-- && ele) { ele = ele.parentNode; } if (! ele || ele.nodeTope ! == 1) return null; return ele; }Copy the code
Returns the NTH sibling of the element
/** * Return the NTH sibling of element ele * if n is positive, return the subsequent NTH sibling * if n is negative, return the previous NTH sibling * if n is zero, / function sibling(ele, n) {while (ele && n! If (el.nextelementSibling) {ele = el.nextelementSibling; } else { for (ele = ele.nextSibling; ele && ele.nodeType ! = = 1; /* void sibling */; } n--; } else {/ / find the previous sibling elements if (ele. PreviousElementSibing) {ele = ele. PreviousElementSibling; } else { for (ele = ele.previousSibling; ele && ele.nodeType ! = = 1; /* void sibling */; } n++; } } return ele; }Copy the code
Returns the NTH child of the element
/** * returns the NTH child of element ele, or null if none exists. 0 is the first child, -1 is the last, -2 is the penultimate, */ function child(ele, n) {if (ele.children) {if (n < 0) n += ele.children. Length; If (n < 0) return null; Ele.children [n]; return ele.children[n]; } // If e does not have the children array, find the first child and count forward, or find the last child and count back if (n >= 0) {//n is non-negative: If (ele.firstelementChild) {ele = ele.firstelementChild; } else { for (ele = ele.firstChild; ele && ele.nodeType ! = = 1; /* void sibling */; } return sibling(ele, n); If (ele.lastelementChild) {ele = ele.lastelementChild; } else { for (ele = ele.lastChild; ele && ele.nodeType ! = = 1; /* void sibling */; } return sibling(ele, n + 1); // to convert the last child element to the last sibling element}}Copy the code
Row sorting of a table
// Sort the first < tBody > row according to the value of the NTH cell in each row of the specified table Function sortrows(table, n, comparator) {var tBody = table.tbodies [0]; / / the first < tbody >, the likelihood is implicitly created var rows = tbody. GetElementsByTagName (" tr "); / / tbody all rows in the rows = Array. The prototype. Slice. The call (rows, 0); / / true snapshots of the array / / based on the value of the first n < td > element to sort rows rows. Sort (function (row1, row2) {var cell1. = row1 getElementsByTagName (" td ") [n]. / / get the NTH cell var cell2 = row2. GetElementsByTagName (" td ") [n]. / / two rows is var val1 = cell1 textContent | | cell1. The innerText; / / get the text contents var val2 = cell2. TextContent | | cell2. The innerText; If (comparator) return comparator(val1, val2); If (val1 < val2) {return -1; } else if (val1 > val2) { return 1; } else { return 0; }}); If < tbody > contains any other elements other than < tr >, these nodes will float to the top position. For (var I = 0; i < rows.length; i++) tbody.appendChild(rows[i]); } // Find the < th > elements of the table (assuming only one row) to make them clickable, // to click the column headers, According to the order of the lines of the column function makeSortable (table) {var headers = table. The getElementsByTagName (" th "); for (var i = 0; i < headers.length; I ++) {(function (n) {headers[I]. Onclick = function () {sortrows(table, n); }; }(i)); // Assign I to the local variable n}}Copy the code
Generate table of contents
/** ** This module registers an anonymous function that runs automatically after the page is loaded. When this function is executed it looks for the element * with id "TOC" in the document. If the element does not exist, create an element * * and the resulting TOC directory should have its own CSS style. The style for the entire directory area is set to "TOCEntry" className * Also we define different styles for different levels of directory titles. The < h1 > tag generates the title *className as "TOCLevel1", the < H2 > tag generates the title *className as "TOCLevel2", and so on * the section number style is "TOCSectNum" * * The complete CSS style code is as follows: * *#TOC{border:solid black 1px; margin:10px; padding:10px; } *.TOCEntry{font-family:sans-serif; } *.TOCEntry a{text-decoration:none; } *.TOCLevel1{font-size:16pt; font-weight:bold; } *.TOCLevel2{font-size:12pt; margin-left:.5in; } *.TOCSectNum:after{content:":"; } * * The last line of this code indicates that each segment number is followed by a colon and a space. To hide the segment number, * use this line: *.tocsectnum {display:none} ** */ (function () {// Anonymous functions define a local scope // find TOC container elements // if not present, Create a var TOC = document.getelementById ("TOC") at the beginning of the document; if (! toc) { toc = document.createElement("div"); toc.id = "TOC"; document.body.insertBefore(toc, document.body.firstChild); // keywords keywords keywords keywords keywords keywords; If (document. QuerySelectorAll) / / if we can use the simple way? headings = document.querySelectorAll("h1,h2,h3,h4,h5,h6"); Keywords keywords = findheading (document.body, []); Keywords keywords (root, sects) {for (var c = root.firstchild; c ! = null; c = c.nextSibling) { if (c.nodeType ! == 1) continue; if (c.tagName.length == 2 && c.tagName.charAt(0) == "H") sects.push(c); else findHeadings(c, sects); } return sects; Var sectionNumbers = [0, 0, 0, 0, 0, 0]; // Now loop through the found title element for (var h = 0; h < headings.length; h++) { var heading = headings[h]; // Skip the heading element in the TOC container if (heading. ParentNode == TOC) continue; Var level = parseInt(heading.tagname.charat (1)); if (isNaN(level) || level < 1 || level > 6) continue; SectionNumbers [level-1]++; sectionNumbers[level-1]++; for (var i = level; i < 6; i++) sectionNumbers[i] = 0; // Now combine all section numbers at the heading level to produce a single section number, 1 var sectionNumber = sectionNumbers.slice(0, level).join(".") Var span = document.createElement("span"); span.className = "TOCSectNum"; span.innerHTML = sectionNumber; heading.insertBefore(span, heading.firstChild); // Wrap the title with named anchors to add links to it var anchor = document.createElement("a"); anchor.name = "TOC" + sectionNumber; heading.parentNode.insertBefore(anchor, heading); anchor.appendChild(heading); Var link = document.createElement("a"); link.href = "#TOC" + sectionNumber; // The target address of the link is link.innerHTML = callout.innerhtml; // Place the link in a div that decorates var Entry = document.createElement("div") with a style based on the level name; entry.className = "TOCEntry TOCLevel" + level; entry.appendChild(link); AppendChild (entry); // Add the div to the TOC container toc.appendChild(entry); }} ());Copy the code
Parse the parameters from the URL
/* * This function parses the name=value pair in the query string from the URL. It stores the name=value pair in the property of an object and returns the object. / var/resolution from the URL parameter * q = args. Q | | ""; // If the parameter is defined, use the parameter; Otherwise use a default *var n=args.n? parseInt(args.n):10; */ function urlArgs() { var args = {}; / / define an empty object var query = location. The search, the substring (1); // find the query string and remove the '? ' var pairs = query.split("&"); For (var I = 0; i < pairs.length; I ++) {// For each fragment var pos = pairs[I].indexof ('='); // find "name=value" if (pos == -1) continue; Var name = pairs[I]. Substring (0, pos); Var value = pairs[I]. Substring (pos + 1); // decodeURIComponent(decodeURIComponent); Args [name] = value; } return args; // Return parsed arguments}Copy the code
Gets the element content of plain text
/** * One argument returns the element's textContent or innerText. InnerText */ function textContent(Element, value) {var Content = element.textContent; If (value === undefined) {// No value passed, so return the current text if (content! == undefined) { return content; } else { return element.innerText; }} else {// Pass value, so set the text if (content! == undefined) { element.textContent = value; } else { element.innerText = value; }}}Copy the code
Hand write a JSONP implementation
// Send a JSONP request to the specified URL // and pass the parsed response data to the callback function // add a query parameter named JSONP to the URL, Function getJSONP(url, callback) {var cbnum = "cb" + getJsonp.counter ++; Var cbname = "getJSONP. // As an attribute of the JSONP function // Add the callback function name to the query part of the URL in form encoding // use JSONP as the parameter name. Some JSONP supporting services // may use other parameter names, such as callback if (url.indexof ("?"). ) === -1) // no query for part of URL += "? jsonp=" + cbname; Else // Otherwise URL += "&jsonp=" + cbName; Var script = document.createElement("script"); var script = document.createElement("script"); // define the callback function to be executed by the script getJSONP[cbnum] = function (response) {try {callback(response); // Handle response data} finally {// Even if the callback function or response throws an error delete getJSONP[cbnum]; / / delete the function script. ParentNode. RemoveChild (script). // Remove script element}}; // Immediately trigger the HTTP request script.src = url; / / setup script the URL of the document. The body. The appendChild (script). } getJsonp.counter = 0; // A counter used to create a unique callback function nameCopy the code
Insert the node
// Insert the child node into the parent, Function insertAt(parent, child, n) { if (n < 0 || n > parent.childNodes.length) { throw new Error("invalid index"); } else if (n == parent.childNodes.length) { parent.appendChild(child); } else { parent.insertBefore(child, parent.childNodes[n]); }}Copy the code
Implement the outerHTML property with innerHTML
// Implement the outerHTML property for browsers that don't support it // Assuming the browser does support innerHTML and has an extensible Element. Prototype, Function () {if (document.createElement("div").outerhtml) return; if (document.createElement("div"). OuterHTMLGetter () {var container = document.createElement("div"); // The virtual element container. AppendChild (this.clonenode (true)); // Copy to the virtual node. Return container.innerhtml; OuterHTMLSetter (value) {// Create a virtual element, Var container = document.createElement("div"); container.innerHTML = value; While (container.firstChild) // loop, Until the container no child nodes this. ParentNode. InsertBefore (container. FirstChild, this); / / remove this is replaced by the node parentNode. RemoveChild (this); } // Now use these two functions as getters and setters for all Element objects' outerHTML properties // If it exists use ES5's object.defineProperty () method, // Otherwise, the next best thing, Use __defineGetter__() and __defineSetter__() if (object.defineProperty) {object.defineProperty (element.prototype, "outerHTML", { get: outerHTMLGetter, set: outerHTMLSetter, enumerable: false, configurable: true }); } else { Element.prototype.__defineGetter__("outerHTML", outerHTMLGetter); Element.prototype.__defineSetter__("outerHTML", outerHTMLSetter); }} ());Copy the code
List the child nodes in reverse order
/ / reverse order to arrange the child nodes of the node n function reverse (n) {/ / create a DocumentFragment as temporary container var f = document. CreateDocumentFragment (); // The last node of n becomes the first node of f, and vice versa // Note that add a node to f, This object automatically deletes from n while (n.lastChild) f.appendChild(n.lastChild); N.apendchild (f); }Copy the code
Query the position of the window scroll bar
/ / in x and y properties of an object to return to the offset of the scroll bar function getScrollOffsets (w) {/ / using the specified window, if with no parameters using the current window w = w | | window; If (w.pagexoffset!) can be used in all browsers except IE 8 and earlier. = null) return { x: w.pageXOffset, y: w.pageYOffset }; // For IE (or any browser) in standard mode var d = w.document; if (document.compatMode == "CSS1Compat") return { x: d.documentElement.scrollLeft, y: d.documentElement.scrollTop }; Return {x: d.bobdy. ScrollLeft, y: d.bobdy. ScrollTop}; }Copy the code
Query the viewport size of a window
/ / as an object of w and h property returns the size of the viewport function getViewportSize (w) {/ / using the specified window, if with no parameters, using the current window w = w | | window; If (w.innerWidth!) is available in all browsers except IE 8 and earlier. = null) return { w: w.innerWidth, h: w.innerHeight }; // For IE (or any browser) in standard mode var d = w.document; if (document.compatMode == "CSS1Compat") return { w: d.documentElement.clientWidth, h: d.documentElement.clientHeight }; Return {w: d.body.clientWidth, h: d.body.clientWidth}; }Copy the code
Returns the name of the function
Function.prototype.getName = function () {
return this.name || this.toString().match(/function\s*(\w*)\s*\(/)[1];
}Copy the code
Native JS implements CSS animation 1
/ / e can be converted to relative positioning element, make it about "vibration" / / the first parameter can be a object or element id / / if the second parameter is a function of e as the parameter, it will call at the end of the animation / / the third parameter specified e shock distance, the default is 5 pixels / / how long the fourth parameter specifies the vibration, Function shake(e, oncomplete, distance, distance) Time) {// Handle argument if (typeof e === "string") e = document.getelementById (e); if (! time) time = 500; if (! distance) distance = 5; var originalStyle = e.style.cssText; // Preserve the original style of e. Position = "relative"; Var start = (new Date()).gettime (); // Animate (); // The animation starts // the function checks the elapsed time and updates the position of E // If the animation is complete, it restores e to its original state // Otherwise, it updates the position of E, Function animate() {var now = (new Date()).getTime(); Elapsed = elapsed; // Elapsed = elapsed; // How long has it taken since we started? var fraction = elapsed / time; // What fraction of the total time? If (fraction < 1) {// If the animation is incomplete // As a function of the animation completion ratio, calculate the x position of e // Use the sine function to multiply the completion ratio by 4pi // so, Var x = distance * math.sin (fraction * 4 * math.pi); e.style.left = x + "px"; // Run the function again after 25 milliseconds or at the last attempt of the total elapsed time in order to generate an animation setTimeout(animate, math.min (25, time-Elapsed)) of 40 frames per second; If (oncomplete) oncomplete(e); if (oncomplete) oncomplete(e); // Call the completed callback function}}}Copy the code
Native JS implements CSS animation 2
function fadeOut(e, oncomplete, time) { if (typeof e === "string") e = document.getElementById(e); if (! time) time = 500; Var ease = math.sqrt; var ease = math.sqrt; var ease = math.sqrt; var ease = math.sqrt; var start = (new Date()).getTime(); // Note: time animate(); Function animate() {elapsed = (new Date()).getTime() - start; Elapsed time = elapsed time; elapsed time = elapsed time; // What fraction of the total time? Var opacity = 1-ease (fraction); // Opacity = 1-ease (fraction); Opacity = String(opacity); SetTimeout (animate, // Next frame math.min (25, elapsed)); Opacity = "0"; opacity = "0"; If (onComplete) oncomplete(e); // Call the completed callback function}}}Copy the code
Mimicking HTML5’s classList attribute
/* * Return e if it has a classList attribute. Otherwise, return an object that emulates the DOMTokenList API for e. * The object returned has methods like Contains (), add(), remove(), toggle(), and toString() * to detect and modify the class collection of element E. If the classList attribute is natively supported, * returns an array-like object with the length and array index attributes. Analog DOMTokenList is not an array-like object, */ function classList(e) {if (e.classList) return e.classList; Else return new CSSClassList(e); // If e.clasList exists, return it else Return new CSSClassList(e); Function CSSClassList(e) {this.e = e; } / / if the lassName of e.c. with our fabrication: contains the name of the class c CSSClassList returns true otherwise returns false. The prototype. The contains = function (c) {/ / check if c is the class name of the legal if (c.l ength = = = 0 || c.indexOf(" ") ! = -1) throw new Error("Invalid class name:'" + c + "'"); Var classes = this.e.className; if (! classes) return false; If (classes === c) return true; Search ("\\b" + c + "\\b")! Return classes.search("\\b" + c + "\\b")! = 1; }; / / if c does not exist, will be added to the e.c. with our fabrication: c lassName CSSClassList. In the prototype. The add = function (c) {if (this. The contains (c)) return; Var classes = this.e.className; if (classes && classes[classes.length - 1] ! = "") c = "" + c; // If you want to add a space this.e.className += c; // add c to className}; / / all c will appear in the lassName of e.c. with our fabrication: delete CSSClassList. Prototype. Remove = function (c) {/ / check if c is the class name of the legal if (c.l ength = = = 0 | | c.i ndexOf (" ")! = -1) throw new Error("Invalid class name:'" + c + "'"); Var pattern = new RegExp("\\b" + c + "\\b\ s*", "g"); this.e.className = this.e.className.replace(pattern, ""); }; // If c does not exist, add c to e.className and return true // Otherwise, all c present in e.className will be deleted, And returns false CSSClassList. Prototype. Toggle = function (c) {if (this. The contains (c)) {/ / if the e.c. with our fabrication: lassName contains c this. Remove (c); // Delete it return false; } else {// otherwise this.add(c); // Add it return true; }}; / / returns the e.c. with our fabrication: CSSClassList lassName itself. The prototype. ToString = function () {return enclosing e.c. with our fabrication: lassName; }; / / returns the name of the class in the lassName of e.c. with our fabrication: CSSClassList. Prototype. ToArray = function () {return enclosing e.c. with our fabrication: lassName. Match (/ \ \ w + b \ b/g) | | []; };Copy the code
Query content in plain text
/** * One argument returns the element's textContent or innerText. InnerText */ function textContent(Element, value) {var Content = element.textContent; If (value === undefined) {// No value passed, so return the current text if (content! == undefined) return content; else return element.innerText; } else {// Passes value, so set the text if (content! == undefined) element.textContent = value; else element.innerText = value; }}Copy the code
The textContent property is supported in all current browsers except IE. In IE, you can use the innerText property of an Element instead. ⬆ back to the top
Find all Text nodes in nodes that are descendants of the element
Function textContent(e) {var child, type, s = ""; For (child = e.firstChild; child ! = null; child = child.nextSibling) { type = child.nodeType; If (type = = = 3 | | type = = = 4) / / Text and CDATASection nodes s + = child. The nodeValue; Else if (type === 1) // Recursive Element s += textContent(child); } return s; }Copy the code
⬆ back to the top
InsertAdjacentHTML () with innerHTML
/ / this module for browsers that do not support it defines the Element. The insertAdjacentHTML / / also defines some portable HTML into the function, their name is more logical than insertAdjacentHTML: // insert.before (), insert.after (), insert.atstart () and insert.atend () var Insert = (function () { // If the element has a native insertAdjacentHTML, If (document.createElement("div").insertadjacenthtml) {return {before: function (e, h) { e.insertAdjacentHTML("beforebegin", h); }, after: function (e, h) { e.insertAdjacentHTML("afterend", h); }, atStart: function (e, h) { e.insertAdjacentHTML("afterbegin", h); }, atEnd: function (e, h) { e.insertAdjacentHTML("beforeend", h); }}; } // Otherwise, no native insertAdjacentHTML // implements the same 4 insert functions and uses them to define insertAdjacentHTML // First, define a tool function that passes in an HTML string and returns a DocumentFragment, Function elt (HTML) {var elt = document.createElement("div"); / var/create an empty element frag = document. CreateDocumentFragment (); // Create an empty document fragment elt.innerhtml = HTML; While (elt.firstChild) // Move all the nodes frag.appendChild(elt.firstchild); // From elt to frag return frag; / / and return to frag} var Insert = {before: function (elt, HTML) {elt. ParentNode. InsertBefore (fragments (HTML), elt); }, after: function (elt, html) { elt.parentNode.insertBefore(fragment(html), elt.nextSibling); }, atStart: function (elt, html) { elt.insertBefore(fragment(html), elt.firstChild); }, atEnd: function (elt, html) { elt.appendChild(fragment(html)); }}; / / based on the above function insertAdjacentHTML Element. The prototype. InsertAdjacentHTML = function (pos, html) { switch (pos.toLowerCase()) { case "beforebegin": return Insert.before(this, html); case "afterend": return Insert.after(this, html); case "afterbegin": return Insert.atStart(this, html); case "beforeend": return Insert.atEnd(this, html); }}; return Insert; }());Copy the code
Drag and drop
/ * * * Drag in js: * This module defines a drag() function, which is used to call the Mousedown event handler * Subsequent mousemove events will move the specified element, These implementations can work with both standard and IE event models. * * Parameters: * *elementToDrag: The element that receives the mouseDown event or some containing element * it must be the positioned element and the style of the element must be inline * its style.left and style.top values will change as the user drags them * *event: Function drag(elementToDrag, event) {var startX = event.clientx; var startY = event.clientY; // Since elementToDrag is absolutely located, Var origX = parseFloat(elementToDrag.style.left); // We can assume that offsetParent is the body element of the document. var origY = parseFloat(elementToDrag.style.top); / / calculate the mousedown event and the distance between the left upper corner of the element / / we'll save it as the distance of the mouse moves the if (document. AddEventListener) {/ / / / standard event model register capture event handlers on the document object document.addEventListener("mousemove", moveHandler, true); document.addEventListener("mouseup", upHandler, true); } else if (document.attachevent) {// If (document.attachevent) { // Capture events by calling setCapture() on elements; elementToDrag.setCapture(); elementToDrag.attachEvent("onmousemove", moveHandler); elementToDrag.attachEvent("onmouseup", upHandler); / / as a mouseup event. Think about the loss of the mouse capture elementToDrag attachEvent (" onlosecapture ", upHandler); If (event.stopPropagation) event.stopPropagation(); if (event.stopPropagation) event.stopPropagation(); Else Event. cancelBubble = true; //IE // now prevent any default actions if (event.preventDefault) event.preventDefault(); Else Event. ReturnValue = false; //IE /** * This is the handler that catches the mousemove event when the element is being dragged ** it moves the element **/ function moveHandler(e) {if (! e) e = window.event; Var targetLeft = e.clientx-startx + origX; var targetLeft = e.clientx-startx + origX; var targetTop = e.clientY - startY + origY; var minLeft = 0; var minTop = 0; var maxLeft = (document.documentElement.clientWidth || document.body.clientWidth) - elementToDrag.offsetWidth; var maxTop = (document.documentElement.clientHeight || document.body.clientHeight) - elementToDrag.offsetHeight; targetLeft = targetLeft > maxLeft ? maxLeft : (targetLeft < minLeft ? minLeft : targetLeft); targetTop = targetTop > maxTop ? maxTop : (targetTop < minTop ? minTop : targetTop); elementToDrag.style.left = targetLeft + "px"; elementToDrag.style.top = targetTop + "px"; if (e.stopPropagation) e.stopPropagation(); Else e.cancelbubble = true; **/ function upHandler(e) {if (! e) e = window.event; / / the event model IE / / cancellation of capture event handler if (document. The removeEventListener) {/ / the DOM event model document. RemoveEventListener (" mouseup ", upHandler, true); document.removeEventListener("mousemove", moveHandler, true); } else if (document. DetachEvent) {/ / IE 5 + event model elementToDrag detachEvent (" onlosecapture ", upHandler); elementToDrag.detachEvent("onmouseup", upHandler); elementToDrag.detachEvent("onmousemove", moveHandler); elementToDrag.releaseCapture(); } // If (e.topPropagation) e.topPropagation (); Else e.cancelbubble = true; //IE } }Copy the code