JavaScript常用脚本集锦8

图片预加载

// 更新:
// 05.27: 1、保证回调执行顺序:error > ready > load;2、回调函数this指向img本身
// 04-02: 1、增加图片完全加载后的回调 2、提高性能

/**
 * 图片头数据加载就绪事件 - 更快获取图片尺寸
 * @version 2011.05.27
 * @author  TangBin(PS:我不是作者,我只是代码的搬运工)
 * @see     http://www.planeart.cn/?p=1121
 * @param   {String}    图片路径
 * @param   {Function}  尺寸就绪
 * @param   {Function}  加载完毕 (可选)
 * @param   {Function}  加载错误 (可选)
 * @example imgReady('http://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {
        alert('size ready: width=' + this.width + '; height=' + this.height);
    });
 */
var imgReady = (function () {
  /*list用来存放onready的函数队列,intervalID用来存放定时器的引用*/
    var list = [], intervalId = null,

    // 用来执行队列
    tick = function () {
        var i = 0;
        for (; i < list.length; i++) {
          /*end用来表示onready函数是否执行完必,splice用来删除队列中的项目*/
            list[i].end ? list.splice(i--, 1) : list[i]();
        };
        //队列全部执行完成后的清除工作。
        !list.length && stop();
    },

    // 停止所有定时器队列,释放内存中的引用
    stop = function () {
        clearInterval(intervalId);
        intervalId = null;
    };
  /**
  * 闭包
  * @param:url  图片的路径
  * @param:ready 图片尺寸就绪的回调函数
  * @param: load 图片加载完毕的回调函数
  * @param: err 图片加载出错的回调函数
  *
  */
    return function (url, ready, load, error) {
        var onready, width, height, newWidth, newHeight,
              img = new Image();

        img.src = url;

        // 如果图片被缓存,则直接返回缓存数据
        if (img.complete) {
            ready.call(img);
            load && load.call(img);
            return;
        };

        width = img.width;
        height = img.height;

        // 加载错误后的事件
        img.onerror = function () {
            error && error.call(img);
            onready.end = true;
            img = img.onload = img.onerror = null;
        };

        // 图片尺寸就绪
        onready = function () {
            newWidth = img.width;
            newHeight = img.height;
            if (newWidth !== width || newHeight !== height ||
                // 如果图片已经在其他地方加载可使用面积检测
                newWidth * newHeight > 1024
            ) {
                ready.call(img);
                onready.end = true;
            };
        };
        onready();

        // 完全加载完毕的事件
        img.onload = function () {
            // onload在定时器时间差范围内可能比onready快
            // 这里进行检查并保证onready优先执行
            !onready.end && onready();

            load && load.call(img);

            // IE gif动画会循环执行onload,置空onload即可
            img = img.onload = img.onerror = null;
        };

        // 加入队列中定期执行
        if (!onready.end) {
            list.push(onready);
            // 无论何时只允许出现一个定时器,减少浏览器性能损耗
            if (intervalId === null) intervalId = setInterval(tick, 40);
        };
    };
})();

代码来源:https://gist.github.com/hehongwei44/5ab040cf3a8b27311d72

js高级截取字符串功能

/**
*
* @descrition: 对字符串进行截取,包括普通字符和中文字符
* @param : str ->待截取的字符串
* @param : len ->要截取的长度
* 
* 比如cutstr('hello',2)->he...  cutstr("您好呀",4)->您好...
* 优先选择后台进行字符串截取,后css截取,最后js截取
*/
var cutstr = function(str, len) {
        var temp,
            icount = 0,
            patrn = /[^\x00-\xff]/g,    //中文字符匹配
            strre = "";

        for (var k = 0; k < str.length; k++) {
            if (icount < len ) {
                temp = str.substr(k, 1);
                if (temp.match(patrn) == null) {
                    icount = icount + 1;
                } else {
                    icount = icount + 2;
                }
                strre += temp;
            } else {
                break
            }
        }
        return strre + "...";
    }

代码来源:https://gist.github.com/hehongwei44/be3027aeb48ab978a039

对javascript中String类型的拓展

/**
*
* @desccrition: 对String类型去除空格的拓展
* @dir : 被去除空格所在的位置
* @test: ie6-9 chrome firefox
*/

String.prototype.trim = function(dir){
        switch (dir) {
            case 0 : //去左边的空格
                return this.replace(/(^\s*)/g,'');
                break;
            case 1 : //去右边的空格
                return this.replace(/(\s*$)/g,'');
                break;
            case 2 : //去掉所有的空格
                return this.replace(/(\s*)/g,'');
                break;
            default : //去掉两边的空格
                return this.replace(/(^\s*)|(\s*$)/g,'');
        }
}

代码来源:https://gist.github.com/hehongwei44/3e167cfcda47d4c8051a

生成随机字符串(数字+字母),长度自定义

/**
* @function:generateRandomAlphaNum->生成随机的字符串
* @param:len->生存随机字符串的长度
* @tdd->IE6-9 chrome Firefox通过测试
* 
*/
function generateRandomAlphaNum(len) {
    var rdmString = "";
    //toSting接受的参数表示进制,默认为10进制。36进制为0-9 a-z
    for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
    return rdmString.substr(0, len);
}

代码来源:https://gist.github.com/hehongwei44/62d64830afa07ddac65f

js通过a标签解析url

/*
* @function: 通过a标签解析url标签
* @param:url  url参数是字符串,解析的目标
  通过IE6-9 chrome  Firefox测试
*
*/

function parseURL(url) {
    //创建一个a标签
    var a =  document.createElement('a');
    //将url赋值给标签的href属性。
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''), //协议
        host: a.hostname,   //主机名称
        port: a.port,   //端口
        query: a.search,  //查询字符串
        params: (function(){  //查询参数
            var ret = {},
                    seg = a.search.replace(/^\?/,'').split('&'),
                    len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1], //文件名
        hash: a.hash.replace('#',''), //哈希参数
        path: a.pathname.replace(/^([^\/])/,'/$1'), //路径
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],  //相对路径
        segments: a.pathname.replace(/^\//,'').split('/') //路径片段
    };
}

代码来源:https://gist.github.com/hehongwei44/46d68bcb75df8cd0495b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值