Home  >  Article  >  Web Front-end  >  Building a JS code base from the basics Page 1/2_javascript skills

Building a JS code base from the basics Page 1/2_javascript skills

PHP中文网
PHP中文网Original
2016-05-16 18:49:43980browse

Since the background program will filter out single quotes, if there are strange spaces in some places, it means single quotes, hereby explain.
/**
* @author Super Sha
* QQ:770104121
* Email:supersha@foxmail.com
* All Rights Reserved!
*/
(function(){ //Original
function $(s){
if (!s)
return false;
return s .constructor == String ? document.getElementById(s) : s;
}
window.$ = $;
})();

(function(){ //Anonymous Encapsulate the function and execute it by itself. The functions or variables defined in this function can be used universally and cannot be accessed outside the function unless you declare it in the namespace
if (!window.Susa)
window[ Susa ] = { }; //Declare the Susa namespace
/*
* Get the reference of the element
*/
function $(){
var elems = new Array();
for ( var i = 0; i < arguments.length; i ) {
var elem = arguments[i];
if (typeof arguments[i] == "string") { //Perform type checking
elem = document.getElementById(arguments[i]);
}
//This has a pun meaning: if a string is passed in and there is only one parameter, or a DOM reference is passed in, both are returned DOM node reference
if (arguments.length == 1) {
return elem;
}
else {
elems.push(elem);
}
}
return elements;
}
window[ Susa ][ $ ] = $;

/*
* Returns child elements within a specific element, or document
*/
function tag(type, elem){
elem = elem || document;
type = type || "*"; //If there are no parameters, return references to all elements of the document
return elem.getElementsByTagName(type);
}
window[ Susa ][ tag ] = tag;

/*
* Return the value of the input box
*/
function value(id){
var elem = $(id); //Call the method defined in the anonymous function
if (elem != null && (elem.nodeName == INPUT || elem.nodeName == TEXTAREA )) {
return elem.value;
}
}
window[ Susa ][ value ] = value;

/*
* can quickly concatenate strings StringBuilder object // (original)
*/
var StringBuilder = {
_arr: new Array,
append: function(str){
if (typeof str == "string" ) {
this._arr.push(str);
}
return this;
},
toString: function(){
if (this._arr.length != 0) {
var strs = this._arr.join( , );
this._arr = []; //Solving the trick of returning repeated additions
return strs;
}
else {
return null;
}
}
}
//function appendString(){
// for(var i=0;i<3;i ){
// StringBuilder.append("test");
// }
// return StringBuilder.toString();
//}
//window[ Susa ][ str ]=appendString ;

/*
* addEvent and moveEvent methods
*/
function addEvent(elem, type, fn){
if (elem != $(elem) || elem == null)
return false;
if (type == null || fn == null)
return false;

if (elem.addEventListener) { //W3C method
elem.addEventListener(type, fn, false);
return true;
}
else
if (elem.attachEvent) {// IE method
//node[ e type fn]=fn;
///node[type fn]=function(){
// node[ e type fn](window.event); //I don’t know why this is done
//}
//node.attachEvent( on type,node[type fn]);
//return this;
elem.attachEvent( on type, function(){
fn.call (elem)
});
//Note: Use an anonymous function here to prevent the this object in IE from pointing incorrectly
return this;
}
else {
elem["on" type] = function(){
fn.call(elem)
};
}
}
function removeEvent(elem, type, fn){
if (elem != $(elem) || elem == null)
return false;
if (type == null || fn == null)
return false;

if (elem.removeEventListener) {//W3C method
elem.removeEventListener(type, fn, false);
return true;
}
else
if (elem.detachEvent) // IE method
{
//node.detachEvent( on type, node[type fn]);
elem.detachEvent( on type, fn);
return this;
}
}
window[ Susa ][ addEvent ] = addEvent;
window[ Susa ][ removeEvent ] = removeEvent;

/*
* The getElementsByClassName method returns a specific References to all elements of the class, tag and elem parameters are optional
*/
function getElementsByClassName(classname, tag, elem){
elem = elem || document;
if ( elem != $(elem) || elem == null)
return false;
//Pay attention to the usage of parent.all of this function. It is used to confirm whether the parent is a document and distinguish IE and Mozilia
if (!tag)
tag = "*";
var allTags = (tag == * && elem.all) ? elem.all : elem.getElementsByTagName(tag);

//Create a regex to detect whether the specified class name is included
classname = classname.replace(/-/g, "\-");
var regex = new RegExp("(^| \s*)" classname "(\s*|$)");

var matchElements = new Array();
var elem;
for (var i = 0; i < allTags.length; i ) {
elem = allTags[i];
if (regex.test(elem.className)) { //Detect class names based on regular rules
matchElements.push(elem);
}
}

return matchElements;
}
window[ Susa ][ getElementsByClassName ] = getElementsByClassName;

/*
* toggleDisplay method, toggle the visibility of HTML tags
*/
function toggleDisplay(id, value){
var elem = $(id);
if (elem != $(elem) || elem == null || elem.nodeType != 1)
return false;
if (elem.style.display != "none") {
elem.style.display = "none";
}
else {
elem.style.display = value || ;
}
return true;
}
window[ Susa ][" toggleDisplay"] = toggleDisplay;

/*
* insertAfter method
*/
function insertAfter(node, referenceNode){
if (node ​​!= $(node) || node == null)
return false;
if (referenceNode != $(referenceNode) || referenceNode == null)
return false;

return referenceNode.parentNode.insertBefore(node , referenceNode.nextSibling); //Pay attention to the insertBefore method. If the second parameter
} // is null, insert it to the end of the parentNode
window[ Susa ][ insertAfter ] = insertAfter;

/*
* removeChildren method, deletes all child elements under the current node
*/
function removeChildren(parent){
if (parent != $(node) || parent == null)
return false;
while (parent.firstChild) { //Loop to delete nodes
parent.firstChild.parentNode.removeChild(node.firstChild);
}
return parent ;
}
window[ Susa ][ removeChildren ] = removeChildren;

/*
* prependChild method, insert the selected node to the front of the current node
*/
function prependChild(parent, newNode){
if (parent != $(parent) || parent == null)
return false;
if (newNode != $(newNode) || newNode == null)
return false;

if (parent.firstChild) { //There is a sub-function when judging
parent.insertBefore(newNode, parent.firstChild);
}
else {
parent.appendChild(newNode);
}
return parent;
}
window[ Susa ][ prependChild ] = prependChild;

/*
* bindFunction() method, used to adjust the execution environment of this
*/
function adjustFunc(obj, func){ //Adjust the execution environment of func to obj
return function(){ / /Return a reference to the anonymous function
func.apply(obj, arguments);
};
}
window[ Susa ][ adjustFunc ] = adjustFunc;

/*
* Get the width and height of the display window, and return an object containing the width and height attributes. It is not public and can only be called by other methods within this anonymous function
*/
function getBrowserWindowSize(){
var de = document.documentElement; //Get the root node
var obj = {
width : (window.innerWidth || (de.clientWidth) || document.body.clientWidth),
height : ( window.innerHeight || (de.clientHeight) || document.body.clientHeight)
}

return obj;
}

/*
* debug log object
*/
function log(id){
id = id || SusaLogWindow ;
var logWindow = null; //Private properties, used in each
var createWindow = function() { //Private method, used to dynamically generate a list node
if (!document.body) {
alert( document.body hasn't finished loading. );
return;
}
var browerWindowSize = getBrowserWindowSize();
var top = ((browerWindowSize.height - 200) / 2) || 0; //Get the position of the upper left corner of the new window in the browser
var left = ((browerWindowSize.width - 200) / 2) || 0;

logWindow = document.createElement( ul ); //Dynamicly generate a UL element
logWindow.setAttribute( id , id );

logWindow.style.position = absolute; //Modify UL elements
logWindow.style.top = top px;
logWindow.style.left = left px;

logWindow.style.width = 250px;
logWindow.style.height = 200px;
logWindow.style.overflow = scroll;

logWindow.style.padding = 0;
logWindow. style.margin = 0;
logWindow.style.border = 1px solid black;
logWindow.style.backgroundColor = white;
logWindow.style.listStyle = none;
logWindow.style.font = 10px/10px Verdana,Tahoma,Sans;

document.body.appendChild(logWindow); //Add dynamically generated nodes to the body
}

this.writeRaw = function (message){ //Privileged method, used to add LI content to the UL node generated by the createWindow method. You need to declare an instance to call
if (!logWindow)
createWindow(); //If the initial window is not If it exists, create it
var li = document.createElement("li"); //Dynamicly generate an LI element
li.style.padding = 2px;
li.style.border = 0;
li.style.borderBottom = 1px dotted black;
li.style.margin = 0 2px;
li.style.color = #000;
li.style.font = 9px/9px Verdana, Tahoma,Sans ;

if (typeof message == undefined ) {
li.appendChild(document.createTextNode( Message was undefined! ));
}
else
if (typeof li.innerHTML != undefined ) {
li.innerHTML = message;
}
else {
li.appendChild(document.createTextNode(message));
}

logWindow.appendChild(li); //Add the generated LI node to the logWindow
return true;
}
}

log.prototype = {
write: function(message){
if (arguments.length == 0) { //warning message The parameter is empty
return this.writeRaw("Lack of params!");
}

if (typeof message != "string") { //If the parameter passed in is not a string , then try to call the toString method. If the access does not exist, record the object type
if (message.toString)
return this.writeRaw(message.toString()); //Pay attention to this judgment method: message. toString. Determine whether an object contains a certain attribute
else
return this.writeRaw(typeof message);
}
message = message.replace(//g, ">"); //Filter <>left and right angle brackets
return this.writeRaw(message);
},
header: function(message){ //Write a header to the log window
message = --> message <-- ;
return this.writeRaw(message);
}
}
window[ Susa ][ log ] = new log( ; Yes, supports multiple parameters // (original)
*/
function debug(){
for (var i = 0; i < arguments.length; i ) {
if (typeof arguments[i] != function ) {
alert("Params sould be Function type!");
return;
}
}
var args = arguments;

(function(){ //Encapsulate the execution function process
try {
for (var i = 0; i < args.length; i ) {
args[i](); //Execution Function
}
}
catch (ex) {
Susa.log.writeRaw( Error: ex.message " Line: " ex.lineNumber);
}
})( );
}
window[ Susa ][ debug ] = debug;

/*
* Declare and determine the constants of node types //Original
*/
window [ Susa ][ node ] = {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSION_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12
};

/*
* Function to detect the extent to which the browser supports DOM Level (original)
*/
function CheckDOMLevel(){
if (document.implementation) { //Determine whether document is supported .implementation property
var DOM = ["Core", "XML", "HTML", "Views", "SytleSheets", "CSS", "CSS2", "Events", "UIEvents", "MouseEvents", "MutationEvent", "HTMLEvents", "Range", "Traversal", "LS", "LS-Async", "Validation"];
var Level = ["1.0", "2.0", "3.0"] ;

for (var i = 0; i < DOM.length; i ) {
for (var j = 0; j < Level.length; j ) {
if (document .implementation.hasFeature(DOM[i], Level[j])) { //document.implementation.hasFeature accepts two parameters
Susa.log.writeRaw("
DOM" Level[j] " " DOM [i] " Supported.
"); } else {
Susa.log.writeRaw("
DOM" Level[j] " " DOM[i] " Not Supported!
") } }
}
}
else {
Susa.log.write("

No DOMImplementation Supported!"); } }
window[ Susa ][ CheckDOMLevel ] = CheckDOMLevel;

/*
* Get and set the value of element properties, you can get getter and Set the setter by calling
*/
function attr(elem, name, value){
if (!name || name.constructor != String)
return ;

//Check whether the name is weirdly named
name = {
for : htmlFor ,
class : className
}[name] ||
name;

if (typeof value != undefined ) {
elem[name] = value; //First use the shortcut
if (elem.setAttribute) { //If possible, use setAttribute
elem.setAttribute( name, value);
}
}
return elem[name] || elem.getAttribute(name) || ; //Return the value of the attribute
}
window[ Susa ][ attr ] = attr;

/*
* Universal function to create new DOM elements
*/
function create(label){
return document.createAttributeNS ? document.createElementNS( http://www.w3.org/1999/xhtml , label) : document.createElement(label); //Return the reference of the newly created element
}
window[ Susa ][ create ] = create;

/*
* Create TextNode node function
*/
//function createText(elem){ // Directly called by DOM elements
// $(elem)==elem ? this.appendChild(elem):this. appendChild(document.createTextNode(elem));
// return this;
//}
function createText(parent, elem){ //(refer to original)
return $(elem) = = elem ? parent.appendChild(elem) : parent.appendChild(document.createTextNode(elem));
}
window["Susa"][ createText ] = createText;

/*
* Insert element before another DOM element // (reference original)
*/
function before(newNode, referenceNode){

if (!newNode && $(referenceNode) != referenceNode)
return false;
var elems = checkElem(newNode); //Get the array to which you want to add node references
for (var i = elems.length - 1; i >= 0; i --) {
referenceNode.parentNode.insertBefore(elems[i], referenceNode);
}
}
window[ Susa ][ before ] = before;

/*
* Append a child element to another element. elem can be a string with an HTML tag, or it can be a reference to the DOM element node // (refer to the original)
*/
function append(parent, elem){
if (!elem && $(parent) != parent)
return false;
var elems = checkElem(elem); //Get the array to which you want to add node references
for (var i = elems.length - 1; i >= 0; i--) {
parent.appendChild(elems[i]);
}
}
window[ Susa ][ append ] = append;

function checkElem(elem){ //Auxiliary functions of before and append functions//(refer to original)
var r = [];
if (elem && elem. constructor == String) { //If the parameter is a string
var p = create("p");
p.innerHTML = elem;
for (var i = p.childNodes.length - 1 ; i >= 0; i--) {
r[r.length] = p.childNodes[i]; //Method to dynamically generate an array
}
}
else
if (elem && elem.constructor == Array) { //If the parameter is an array
var p = create("p");
p.innerHTML = elem.join( );
for ( var i = p.childNodes.length - 1; i >= 0; i--) {
r[r.length] = p.childNodes[i]; //Method to dynamically generate arrays
}
}
else
if (elem && $(elem) == elem) { //If it is a DOM node
r[r.length] = elem;
}
return r;
}

/*
* Delete all content within the DOM element. The parameter can be a DOM node reference or an HTML ID tag
*/
function empty( elem){
elem = transformLabelID(elem);
while (elem.firstChild) {
elem.removeChild(elem.firstChild);
}
}
window["Susa "][ empty ] = empty;

/*
* html function, which can get and set DOM elements. elem can be a string or a reference to a DOM element // (original)
*/
function html(parent, elem){
parent = transformLabelID(parent);
if (elem && $(elem) == elem) {
parent.innerHTML = elem. innerHTML;
return parent;
}
else {
return elem && elem.constructor == String ? parent.innerHTML = elem : parent.innerHTML;
}
}
window["Susa"]["html"] = html;

/*
* General function to get the text content of the element, both getting and setting can be used
*/
function text (e){
e = transformLabelID(e);
if (arguments[1]) {
e.innerHTML = arguments[1];
}
else {
var t = "";
e = e.childNodes || e; //If an element is passed in, continue traversing its child elements, otherwise it is assumed to be an array
for (var j = 0; j < e.length; j ) {
t = e[j].nodeType != 1 ? e[j].nodeValue : text(e[j]); //Recursively call the text function
}
return t;
}
}
window[ Susa ][ text ] = text;

/*
* outerHTML and outerText methods similar to innerHTML and innerText // Original
*/
function outerText(elem, t){
elem = transformLabelID(elem);
//Check whether it is a DOM node or a text string
if (t) {
var el = t.constructor == String ? document.createTextNode(t) : t;
elem.parentNode.insertBefore(el, elem); //Insert node
elem.parentNode before the current element. removeChild(elem); //Delete the current node later
}
else {
return text(elem); //If the second parameter is empty, return the current Text
}

}
function outerHTML(elem, h){
elem = transformLabelID(elem);
if (h) {
var elems = checkElem(h); //return h string or array of nodes
for (var i = elems.length - 1; i >= 0; i--) {
elem.parentNode.insertBefore(elems[i], elem);
}
elem.parentNode.removeChild(elem);
}
else {
var p = create("p");
p.appendChild(elem);
return p.innerHTML;
}
}
window["Susa"]["outerText"] = outerText;
window[Susa]["outerHTML"] = outerHTML;

/*
* wrag wraps the current element with another element // Original
*/
function wrag(elem, wragLabel, attrProp){
elem = transformLabelID(elem);
var next = elem.nextSibling || document.body; //Get the next adjacent element of the elem element. If it does not exist, set it to body
var w = create(wragLabel); // Generate a new one Element, used to contain the current element
for (var o in attrProp) { //Set the attributes of the new element
w.setAttribute(o, attrProp[o]);
}
w.appendChild (elem);
next == document.body ? document.body.appendChild(w) : next.parentNode.insertBefore(w, next); //Insert the containing element into the document
}
window ["Susa"]["wrag"] = wrag;

/*
* Convert parameters to HTML ID tags to DOM node references //Original
*/
function transformLabelID(str ){
return !str ? false : $(str);
}

/*
* Delete a single DOM node. The parameter can be a node reference or an HTML ID tag. Value // (original)
*/
function remove(elem){
transformLabelID(elem).parentNode.removeChild(transformLabelID(elem));
}
window[ Susa ][ remove ] = remove;

/*
* clone function returns a copy of the DOM element. The parameter can be a node reference or an HTML ID tag value // (original)
*/
function clone(elem){
return transformLabelID(elem).cloneNode(true);
}
window[ Susa ][ clone ] = clone;

/*
* Universal function to prevent time bubbling
*/
function stopBubble(e){
if (e && e.stopPropagation) { //If parameters are passed in, it is a w3c method
e.stopPropagation();
}
else {
window.event.cancelBubble = true; //IE method
}
}
window[ Susa ][ stopBubble ] = stopBubble;

/*
* Universal function to prevent default browser behavior
*/
function stopDefault(e){
if (e && e.preventDefault) { / /W3C method
e.preventDefault();
}
else {
window.event.returnValue = false; //IE method
}
return false;
}
window["Susa"]["stopDefault"] = stopDefault;

/*
* Function to get the real and final css style attribute value of the element
*/
function getStyle(elem, name){
elem = transformLabelID(elem); //The parameter elem can be a DOM reference or
if (elem.style[name]) { //If the attribute exists and style[ ], then it has been set (and is current)
return elem.style[name];
}
else
if (elem.currentStyle) { // Otherwise, try to use IE's method
return elem.currentStyle[name];
}
else
if (document.defaultView && document.defaultView.getComputedStyle) { //Or W3C's method, if it exists
//It uses the general 'text-align' style rule instead of textAlign
name = name.replace(/([A-Z])/g, "-$1");
name = name. toLowerCase();
return document.defaultView.getComputedStyle(elem, null).getPropertyValue(name);

}
else {
return null;
}
}
window["Susa"][ getStyle ] = getStyle;

/*
*Function to convert word-word into wordWord format
*/
function camelize(s) {
return s.replace(/-(w)/g, function(strMatch, p){
return p.toUpperCase();
});
}

/*
* Set the css style of the element, the parameter is an object (original)
*/
function setStyle(elem, obj){
elem = transformLabelID(elem);
for ( var o in obj) { //Traverse the properties of the obj parameter
elem.style[o] = obj[o]; //Set the css style
}
}
window[ Susa ] [ setStyle ] = setStyle;

/*
* css function, which can be getter and setter, returns the css style of a specific element // (original)
*/
function css(elem, obj){
elem = transformLabelID(elem);
if (elem && (typeof obj == "string")) {
return getStyle(elem, obj); //Call the getStyle function and get The value of a specific css style
}
else
if (typeof obj == "object") {
for (var o in obj) {
elem.style[o] = obj [o];
}
}
}
window[ Susa ][ css ] = css;

/*
* Merge two objects and merge the results Integrate into the first object //Original
*/
function mergeObj(obj1, obj2){
if ((typeof obj1 == "Object") && (typeof obj2 == "Object"))
return false;
for (var o in obj2) {
obj1[o] = obj2[o];
}
return obj1;
}
window[" Susa"]["mergeObj"] = mergeObj;

/*
* Pass in several function references, take the nearest function without errors and execute it (original)
*/
function $try(){
for (var i = 0; i < arguments.length; i ) {
try {
return arguments[i](); //Execute parameter function
}
catch (ex) {
continue;
}
}
}
window["Susa"]["$try"] = $try;

Statement:
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