Front end code set

  css, html5, javascript, jquery

HTML5

  1. Using FileReader to Preview Front-end Pictures
  2. How to get all checkbox in the page? (No Third Party Framework)
  3. JavaScript Template Engine Instances

Javascript

  1. Implement JS function overload
  2. JS Cross Browser Binding Event Function
  3. JS monomer mode
  4. Object method defined using prototype property
  5. Closure Implements Result Caching
  6. Closures Implement Encapsulation
  7. Closures Implement Classes and Inheritance
  8. How to judge whether a variable is an array data type?
  9. Javascript inheritance-borrowing constructors
  10. Javascript prototype-encapsulation
  11. Correct the function’s context through closures (bind browser does not support solutions)
  12. Optimize JavaScript’s constructor (use of new keyword)
  13. Corellian
  14. Object Copy and Assignment

CSS

  1. Center
  2. Menu bar drop-down

JQuery

  1. JQ Sets Columns of Equal Height

HTML5

Using FileReader to Preview Front-end Pictures

<input type="file"><br>
<img src="" height="200" alt="Image preview area..." title="preview-img">
var fileInput = document.querySelector('input[type=file]');
var previewImg = document.querySelector('img');

fileInput.addEventListener('change', function () {
    var file = this.files[0];
    var reader = new FileReader();

    reader.addEventListener('load', function () {
        previewImg.src = reader.result;
    }, false);

    reader.readAsDataURL(file);
}, false);

How to get all checkbox in the page? (No Third Party Framework)

var doc = document,
    domList = doc.getElementsByTagName('input'),
    checkBoxList = [],
    len = domList.length;

while (len--) {
    if (domList[len].type === 'checkbox') {
        checkBoxList.push(domList[len]);
    }
}

JavaScript Template Engine Instances

<div class="result"></div>
<script type="template" id="template">
    <h2>
        <a href="{{href}}">
            {{title}}
        </a>
    </h2>
    <img src="{{imgSrc}}" width="300" height="100" alt="{{title}}"/>
</script>

Data

var data = [
    {
        title: "",
        href: "",
        imgSrc: ""
    },
    ...
];

Method 1:

var doc = document,
    template = doc.querySelector('#template').innerHTML,
    result = doc.querySelector('.result'),
    fragment = '';

for (var i = 0, len = data.length; i < len; i++) {
    fragment += template
        .replace(/\{\{title\}\}/, data[i].title)
        .replace(/\{\{href\}\}/, data[i].href)
        .replace(/\{\{imgSrc\}\}/, data[i].imgSrc)
}

result.innerHTML = fragment;

Method 2:

var doc = document,
    template = doc.querySelector('#template').innerHTML,
    result = doc.querySelector('.result'),
    attachTemplateToData;

attachTemplateToData = function (template, data) {
    var i = 0,
        len = data.length,
        fragment = '';

    function replace(obj) {
        var t, key, reg;

        for (key in obj) {
            reg = new RegExp('{{' + key + '}}', 'ig');
            t = (t || template).replace(reg, obj[key]);
        }

        return t;
    }

    for (; i < len; i++) {
        fragment += replace(data[i]);
    }

    return fragment;
};

result.innerHTML = attachTemplateToData(template, data);

JavaScript

Implement JS function overload

var people = {
    values: ["Dean Edwards", "Sam Stephenson", "Alex Russell", "Dean Tom"]
};

function addMethod(object, name, fn) {
    var old = object[name];
    object[name] = function () {
        if (fn.length === arguments.length) {
            return fn.apply(this, arguments);
        } else if (typeof old === 'function') {
            return old.apply(this, arguments);
        }
    }
}

addMethod(people, "find", function () {
    return this.values;
});

addMethod(people, "find", function (firstName) {
    var ret = [];
    for (var i = 0; i < this.values.length; i++) {
        if (this.values[i].indexOf(firstName) === 0) {
            ret.push(this.values[i]);
        }
    }
    return ret;
});

addMethod(people, "find", function (firstName, lastName) {
    var ret = [];
    for (var i = 0; i < this.values.length; i++) {
        if (this.values[i] === (firstName + ' ' + lastName)) {
            ret.push(this.values[i]);
        }
    }
    return ret;
});

console.log(people.find());
console.log(people.find("Sam"));
console.log(people.find("Dean Edwards"));

JS Cross Browser Binding Event Function

Conventional implementation method

//跨浏览器添加事件
function addHandler(target, eventType, handler) {
    //检测浏览器类型,并且重写addHandler方法
    if (target.addEventListener) {
        addHandler = function (target, eventType, handler) {
            target.addEventListener(eventType, handler, false);
        }
    } else { //IE
        addHandler = function (target, eventType, handler) {
            target.attachEvent("on" + eventType, handler);
        }
    }

    //调用新的函数
    addHandler(target, eventType, handler);
}

//跨浏览器移除事件
function removeHandler(target, eventType, handler) {
    //检测浏览器类型,并且重写addHandler方法
    if (target.addEventListener) {
        removeHandler = function (target, eventType, handler) {
            target.removeEventListener(eventType, handler, false);
        }
    } else { //IE
        removeHandler = function (target, eventType, handler) {
            target.detachEvent("on", eventType, handler);
        }
    }

    target.detachEvent("on" + eventType, handler);
}

Optimization method

//绑定事件
var addHandler = document.body.addEventListener ?
    function (target, eventType, handler) {//DOM2
        target.addEventListener(eventType, handler, false);
    } :
    function (target, eventType, handler) {//IE
        target.attachEvent("on" + eventType, handler);
    };

//移除事件
var removeHandler = document.body.removeEventListener ?
    function (target, eventType, handler) {
        target.removeEventListener(eventType, handler, false);

    } :
    function (target, eventType, handler) {
        target.detachEvent("on" + eventType, handler);
    };

JS monomer mode

var shoppingCar = (function () {
    //这个是由购物车构造器所创建的实例
    var instance;

    //购物车的构造器函数 
    function Trolley() {
        this.date = new Date().getDate();//实例属性,当前日期
    }

    //原型属性,一个返回当前日期的方法
    Trolley.prototype.getDate = function () {
        return this.date;
    };

    //暴露出去的公共API
    return function () {
        //如果实例不存在,那么就调用Trolley构造器实例化一个
        if (!instance) {
            instance = new Trolley();
        }

        //将实例返回外部
        return instance;
    }
}());

var a = new shoppingCar();
var b = new shoppingCar();
console.log(a === b);//true

Object method defined using prototype property

var dom = function () {};

dom.Show = function () {
    alert("Show Message");
};

dom.prototype.Display = function () {
    alert("Property Message");
};

dom.Display(); //error
dom.Show(); //Show Message
var d = new dom();
d.Display(); //Property Message
d.Show(); //error

1. Object methods that are not defined by the prototype attribute are static methods and can only be called directly with class names! In addition, this variable cannot be used in this static method to call other properties of the object!

2. Object methods defined using the prototype attribute are non-static methods and can only be used after instantiation! This can be used inside its method to refer to other attributes in the object itself!

Closure Implements Result Caching

var CachedSearchBox = (function () {
    var cache = {},
        table = [];

    return {
        attachSearchBox: function (dsid) {
            if (dsid in cache) { //如果结果在缓存中
                return cache[dsid]; //直接返回缓存中的对象
            }
            var fsb = new uikit.webctrl.SearchBox(dsid);//新建
            cache[dsid] = fsb;//更新缓存
            if (count.length > 100) {
                delete cache[shift()];
            }
            return fsb;
        },

        clearSearchBox: function (dsid) {
            if (dsid in cache) {
                cache[dsid].clearSelection();
            }
        }
    }
})();

CachedSearchBox.attachSearchBox('input');

We will encounter many situations in our development. Imagine that we have a function object that takes a long time to process. Each call will take a long time.

Then we need to store the calculated value. When calling this function, we first look it up in the cache. If we can’t find it, we calculate it. Then we update the cache and return the value. If we find it, we can directly return the found value. Closures do this precisely because they do not release external references so that values inside functions can be preserved.

Closures Implement Encapsulation

var person = function () {
    var name = "Default";

    return {
        getName: function () {
            return name;
        },
        setName: function (newName) {
            name = newName;
        }
    }
}();

console.log(person.name);//undefined
console.log(person.getName());//Default
person.setName("GoodMan");
console.log(person.getName());//GoodMan

Closures Implement Classes and Inheritance

function Person() {
    var name = "default";

    return {
        getName: function () {
            return name;
        },
        setName: function (newName) {
            name = newName;
        }
    }
}

var p = new Person();
p.setName('Tom');
console.log(p.getName());
var Jack = function () {
};
Jack.prototype = new Person();//继承自Person
Jack.prototype.Say = function () { //添加私有方法
    console.log("Hello,my name is Jack");
};
var j = new Jack();
j.setName("Jack");//Tom
j.Say();//Hello,my name is Jack
console.log(j.getName());//Jack

How to judge whether a variable is an array data type

if (typeof Array.isArray === "undefined") {
    Array.isArray = function (arg) {
        return Object.prototype.toString.call(arg) === "[object Array]"
    };
}

Javascript inheritance-borrowing constructors

var Widget = function (name) {
    this.messages = [];
};

Widget.prototype.type = 'Widget';

var SubWidget = function (name) {
    Widget.apply(this, Array.prototype.slice.call(arguments));
    this.name = name;
};

SubWidget.prototype = Widget.prototype;

var sub1 = new SubWidget('foo');
var sub2 = new SubWidget('bar');

sub1.messages.push('foo');
sub2.messages.push('bar');

console.log(sub1.messages);//foo
console.log(sub2.messages);//bar

Javascript prototype-encapsulation

var Dialog = (function () {
    function Dialog() {
    }

    Dialog.prototype = {
        init: function () {
            console.log("ok");
        }
    };

    return Dialog;
}());

var d = new Dialog();
d.init();//ok

Correct the context of the function through closures (browsers do not support solutions)

if (!('bind' in Function.prototype)) {
    Function.prototype.bind = function () {
        var fn = this,
            context = arguments[0],
            args = Array.prototype.slice.call(arguments, 1);

        return function () {
            return fn.apply(context, args.concat(arguments));
        }
    }
}

Optimize JavaScript’s constructor (use of new keyword)

方法一:
function User(name, age) {
    if (typeof Object.create === 'undefined') {
        Object.create = function (prototype) {
            function C() {
                C.prototype = prototype;
                return new C();
            }
        }
    }
    var self = this instanceof User ? this : Object.create(User.prototype);
    self.name = name;
    self.age = age;
    return self;
}


方法二:
function Programmer(name, company, expertise) {
    if (!(this instanceof Programmer)) {
        return new Programmer(name, company, expertise);
    }

    this.name = name;
    this.company = company;
    this.expertise = expertise;

    this.writeCode = function () {
        console.log("Writing some public static thing..")
    }
}

Corellian

var curry = function (fn) {
    var limit = fn.length;
    return function judgeCurry(...args) {
        return function (...args) {
            if (args.length >= limit) {
                return fn.apply(null, args);
            } else {
                return function (...args2) {
                    return judgeCurry.apply(null, args.concat(args2))
                }
            }
        }
    }
};

var currySingle = fn => judgeCurry = (...args) => args.length >= fn.length ? fn.apply(null, args) : (...args2) => judgeCurry.apply(null, args.concat(args2));

Object Copy and Assignment

var obj = {
    name: 'xiaoming',
    age: 23
};
var newObj = obj;
newObj.name = 'xiaohua';
console.log(obj.name);//xiaohua
console.log(newObj.name);//xiaohua

We willobjObject is assigned tonewObjObject to change thenewObjThenameProperty, butobjObject’snameThe attribute has also been tampered with because in factnewObjObject gets only a memory address, not a real copy, soobjThe object has been tampered with.

var obj = {
    name: 'xiaoming',
    age: 23
};
var newObj = Object.assign({}, obj, {color: 'blue'});
newObj.name = 'xiaohua';
console.log(obj.name);//xiaoming
console.log(newObj.name);//xiaohua
console.log(newObj.color);//blue

utilizeObject.assign()Method to execute theDeep copyThe possibility of tampering with the source object can be avoided. Because ..Object.assign()The method can copy any number of enumerable attributes of the source object itself to the target object, and then return the target object.

var obj = {
    name: 'xiaoming',
    age: 23
};
var newObj = Object.create(obj);
newObj.name = 'xiaohua';
console.log(obj.name);//xiaoming
console.log(newObj.name);//xiaohua

We can also use itObject.create()Method to copy objects,Object.create()Method to create a new object with the specified prototype object and attributes.

CSS

Center

#main {
    width: 440px;
    margin: 0 auto;
    position: relative;
    text-align: center;
}

Menu bar drop-down

.menu > li {
    display: block;
    float: left;
    position: relative;
}

JQuery

JQ Sets Columns of Equal Height

<div class="equalHeight" style="border: 1px solid">
    <p>First Line</p>
    <p>Second Line</p>
    <p>Third Line</p>
</div>
<div class="equalHeight" style="border: 1px solid">
    <p>Column Two</p>
</div>
$(function () {
    equalHeight(".equalHeight");
});

var maxHeight = 0;

function equalHeight(col) {
    col = $(col);
    col.each(function () {
        if ($(this).height() > maxHeight) {
            maxHeight = $(this).height()
        }
    });
    col.height(maxHeight);
}