前端代码集

来源:互联网 发布:赵丽颖林更新网络剧 编辑:程序博客网 时间:2024/06/11 12:36

HTML5

使用FileReader实现前端图片预览

<input type="file"><br>
<img src=""height="200"alt="Image preview area..." title="preview-img">
varfileInput = document.querySelector('input[type=file]');
varpreviewImg = document.querySelector('img');
fileInput.addEventListener('change',function() {
    varfile = this.files[0];
    varreader = newFileReader();
    reader.addEventListener('load',function() {
        previewImg.src = reader.result;
    },false);
    reader.readAsDataURL(file);
},false);

取到页面中所有的checkbox怎么做?(不使用第三方框架)

vardoc = document,
    domList = doc.getElementsByTagName('input'),
    checkBoxList = [],
    len = domList.length;
while(len--) {
    if(domList[len].type === 'checkbox') {
        checkBoxList.push(domList[len]);
    }
}

JavaScript模版引擎小实例

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

数据

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

方法一:

vardoc = document,
    template = doc.querySelector('#template').innerHTML,
    result = doc.querySelector('.result'),
    fragment = '';
for(vari = 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;

方法二:

vardoc = document,
    template = doc.querySelector('#template').innerHTML,
    result = doc.querySelector('.result'),
    attachTemplateToData;
attachTemplateToData = function(template, data) {
    vari = 0,
        len = data.length,
        fragment = '';
    functionreplace(obj) {
        vart, key, reg;
        for(key inobj) {
            reg = newRegExp('{{'+ key + '}}','ig');
            t = (t || template).replace(reg, obj[key]);
        }
        returnt;
    }
    for(; i < len; i++) {
        fragment += replace(data[i]);
    }
    returnfragment;
};
result.innerHTML = attachTemplateToData(template, data);

JavaScript

实现JS函数重载

varpeople = {
    values: ["Dean Edwards","Sam Stephenson","Alex Russell","Dean Tom"]
};
functionaddMethod(object, name, fn) {
    varold = object[name];
    object[name] = function() {
        if(fn.length === arguments.length) {
            returnfn.apply(this, arguments);
        }elseif (typeofold === 'function') {
            returnold.apply(this, arguments);
        }
    }
}
addMethod(people,"find",function() {
    returnthis.values;
});
addMethod(people,"find",function(firstName) {
    varret = [];
    for(vari = 0; i < this.values.length; i++) {
        if(this.values[i].indexOf(firstName) === 0) {
            ret.push(this.values[i]);
        }
    }
    returnret;
});
addMethod(people,"find",function(firstName, lastName) {
    varret = [];
    for(vari = 0; i < this.values.length; i++) {
        if(this.values[i] === (firstName + ' ' + lastName)) {
            ret.push(this.values[i]);
        }
    }
    returnret;
});
console.log(people.find());
console.log(people.find("Sam"));
console.log(people.find("Dean Edwards"));

JS跨浏览器绑定事件函数

常规实现方法

//跨浏览器添加事件
functionaddHandler(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);
}
//跨浏览器移除事件
functionremoveHandler(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);
}

优化方法

//绑定事件
varaddHandler = document.body.addEventListener ?
    function(target, eventType, handler) {//DOM2
        target.addEventListener(eventType, handler, false);
    } :
    function(target, eventType, handler) {//IE
        target.attachEvent("on"+ eventType, handler);
    };
//移除事件
varremoveHandler = document.body.removeEventListener ?
    function(target, eventType, handler) {
        target.removeEventListener(eventType, handler, false);
    } :
    function(target, eventType, handler) {
        target.detachEvent("on"+ eventType, handler);
    };

JS单体模式

varshoppingCar = (function() {
    //这个是由购物车构造器所创建的实例
    varinstance;
    //购物车的构造器函数 
    functionTrolley() {
        this.date = newDate().getDate();//实例属性,当前日期
    }
    //原型属性,一个返回当前日期的方法
    Trolley.prototype.getDate = function() {
        returnthis.date;
    };
    //暴露出去的公共API
    returnfunction () {
        //如果实例不存在,那么就调用Trolley构造器实例化一个
        if(!instance) {
            instance = newTrolley();
        }
        //将实例返回外部
        returninstance;
    }
}());
vara = newshoppingCar();
varb = newshoppingCar();
console.log(a === b);//true

使用prototype属性定义的对象方法

vardom = function() {};
dom.Show = function() {
    alert("Show Message");
};
dom.prototype.Display = function() {
    alert("Property Message");
};
dom.Display();//error
dom.Show();//Show Message
vard = newdom();
d.Display();//Property Message
d.Show();//error

1、不使用prototype属性定义的对象方法,是静态方法,只能直接用类名进行调用!另外,此静态方法中无法使用this变量来调用对象其他的属性!

2、使用prototype属性定义的对象方法,是非静态方法,只有在实例化后才能使用!其方法内部可以this来引用对象自身中的其他属性!

闭包实现结果缓存

varCachedSearchBox = (function() {
    varcache = {},
        table = [];
    return{
        attachSearchBox:function(dsid) {
            if(dsid incache) { //如果结果在缓存中
                returncache[dsid]; //直接返回缓存中的对象
            }
            varfsb = newuikit.webctrl.SearchBox(dsid);//新建
            cache[dsid] = fsb;//更新缓存
            if(count.length > 100) {
                deletecache[shift()];
            }
            returnfsb;
        },
        clearSearchBox:function(dsid) {
            if(dsid incache) {
                cache[dsid].clearSelection();
            }
        }
    }
})();
CachedSearchBox.attachSearchBox('input');

我们开发中会碰到很多情况,设想我们有一个处理过程很耗时的函数对象,每次调用都会花费很长时间,

那么我们就需要将计算出来的值存储起来,当调用这个函数的时候,首先在缓存中查找,如果找不到,则进行计算,然后更新缓存并返回值,如果找到了,直接返回查找到的值即可。闭包正是可以做到这一点,因为它不会释放外部的引用,从而函数内部的值可以得以保留。

闭包实现封装

varperson = function() {
    varname = "Default";
    return{
        getName:function() {
            returnname;
        },
        setName:function(newName) {
            name = newName;
        }
    }
}();
console.log(person.name);//undefined
console.log(person.getName());//Default
person.setName("GoodMan");
console.log(person.getName());//GoodMan

闭包实现类和继承

functionPerson() {
    varname = "default";
    return{
        getName:function() {
            returnname;
        },
        setName:function(newName) {
            name = newName;
        }
    }
}
varp = newPerson();
p.setName('Tom');
console.log(p.getName());
varJack = function() {
};
Jack.prototype = newPerson();//继承自Person
Jack.prototype.Say = function() { //添加私有方法
    console.log("Hello,my name is Jack");
};
varj = newJack();
j.setName("Jack");//Tom
j.Say();//Hello,my name is Jack
console.log(j.getName());//Jack

如何判断某变量是否为数组数据类型

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

Javascript继承-借用构造函数

varWidget = function(name) {
    this.messages = [];
};
Widget.prototype.type = 'Widget';
varSubWidget = function(name) {
    Widget.apply(this, Array.prototype.slice.call(arguments));
    this.name = name;
};
SubWidget.prototype = Widget.prototype;
varsub1 = newSubWidget('foo');
varsub2 = newSubWidget('bar');
sub1.messages.push('foo');
sub2.messages.push('bar');
console.log(sub1.messages);//foo
console.log(sub2.messages);//bar

Javascript原型-封装

varDialog = (function() {
    functionDialog() {
    }
    Dialog.prototype = {
        init:function() {
            console.log("ok");
        }
    };
    returnDialog;
}());
vard = newDialog();
d.init();//ok

通过闭包修正函数的上下文(浏览器不支持解决方案)

if(!('bind'in Function.prototype)) {
    Function.prototype.bind = function() {
        varfn = this,
            context = arguments[0],
            args = Array.prototype.slice.call(arguments, 1);
        returnfunction () {
            returnfn.apply(context, args.concat(arguments));
        }
    }
}
优化JavaScript的构造函数(new关键字的使用)
 
方法一:
functionUser(name, age) {
    if(typeofObject.create === 'undefined') {
        Object.create = function(prototype) {
            functionC() {
                C.prototype = prototype;
                returnnew C();
            }
        }
    }
    varself = thisinstanceof User ? this: Object.create(User.prototype);
    self.name = name;
    self.age = age;
    returnself;
}
方法二:
functionProgrammer(name, company, expertise) {
    if(!(thisinstanceof Programmer)) {
        returnnew Programmer(name, company, expertise);
    }
    this.name = name;
    this.company = company;
    this.expertise = expertise;
    this.writeCode = function() {
        console.log("Writing some public static thing..")
    }
}

柯里化

varcurry = function(fn) {
    varlimit = fn.length;
    returnfunction judgeCurry(...args) {
        returnfunction (...args) {
            if(args.length >= limit) {
                returnfn.apply(null, args);
            }else{
                returnfunction (...args2) {
                    returnjudgeCurry.apply(null, args.concat(args2))
                }
            }
        }
    }
};
varcurrySingle = fn => judgeCurry = (...args) => args.length >= fn.length ? fn.apply(null, args) : (...args2) => judgeCurry.apply(null, args.concat(args2));

对象拷贝与赋值

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

我们将obj对象赋值给了newObj对象,从而改变newObj的name属性,但是obj对象的name属性也被篡改,这是因为实际上newObj对象获得的只是一个内存地址,而不是真正的拷贝,所以obj对象被篡改。

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

利用Object.assign()方法进行对象的

深拷贝

可以避免源对象被篡改的可能。因为Object.assign()方法可以把任意多个的源对象自身的可枚举属性拷贝给目标对象,然后返回目标对象。

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

我们也可以使用Object.create()方法进行对象的拷贝,Object.create()方法可以创建一个具有指定原型对象和属性的新对象。

CSS

居中

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

菜单栏下拉

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

JQuery

Q设置等高的列

<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");
});
varmaxHeight = 0;
functionequalHeight(col) {
    col = $(col);
    col.each(function() {
        if($(this).height() > maxHeight) {
            maxHeight = $(this).height()
        }
    });
    col.height(maxHeight);

作者:寒青
原文:https://segmentfault.com/a/1190000011614760#articleHeader9

原创粉丝点击