TracerLee / tracerlee.github.io

Personal blog written by Tracer
4 stars 0 forks source link

Javascript小代码 #8

Open TracerLee opened 8 years ago

TracerLee commented 8 years ago

Javascript代码片段收集

旨在通过日常的开发中汲取一些可贵的代码片段,方便查阅和复习。

TracerLee commented 7 years ago

按钮快速点击

/**
 * 阻止按钮快速点击,默认300ms缓冲时间
 * @param  {Object}   t        this对象
 * @param  {Function} callback 回调函数
 * @param  {Number}   delay    延迟时间
 */
holdClick: function (t, callback, delay) {
    delay = delay || 300;

    if(!t.timeout){
        t.timeout = true;
        callback && callback();
    }else {
        console.warn('按得太快啦');
    }

    setTimeout(function() {
        t.timeout = false;
    }, delay);
}
TracerLee commented 7 years ago

JQuery Free

TracerLee commented 7 years ago

Javascript控制锚点跳转

location.hash = '';
location.hash = 'anchor';
TracerLee commented 7 years ago

获取url参数

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
TracerLee commented 7 years ago

移动端禁止滑动

$(selector).on('touchmove', function (e) {
    e.preventDefault();
});

PC端禁止滑动

.ovfHiden{overflow: hidden;height: 100%;}
$('html,body').addClass('ovfHiden'); //使网页不可滚动
$('html,body').removeClass('ovfHiden'); //使网页恢复可滚动
TracerLee commented 7 years ago

上报统计

function log(id, async) {
    async = async || true;
    if(async){//异步
        try {
            setTimeout(function(){
                (new Image()).src = "http://xxx.com/front/link.php?id=" + id + "&d=" + Math.random();
            },0);
        } catch (ex) { }
    } else {
        try {
            (new Image()).src = "http://xxx.com/front/link.php?id=" + id + "&d=" + Math.random();
        } catch (ex) { }
    }
}
TracerLee commented 7 years ago

操纵浏览器的历史记录

添加和修改历史记录条目

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

假设现在用户导航到了http://google.com,然后点击了后退按钮,此时,地址栏将会显示http://mozilla.org/bar.html,并且页面会触发popstate事件,该事件中的状态对象(state object)包含stateObj的一个拷贝。该页面看起来像foo.html,尽管页面内容可能在popstate事件中被修改。

参考资料:

TracerLee commented 7 years ago

常用正则

手机号验证

var validate = function(num) {
    var exp = /^1[3-9]\d{9}$/;
    return exp.test(num);
};

身份证号验证

var exp = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;

ip验证

var exp = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
TracerLee commented 7 years ago

操作cookie

function setCookie (cname, cvalue, exdays){
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = 'expires='+d.toUTCString();
    document.cookie = cname + '=' + cvalue + '; ' + expires;
};
function getCookie (cname) {
    var name = cname + '=';
    var ca = document.cookie.split(';');
    for(var i=0; i< ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return '';
};
TracerLee commented 7 years ago

生成随机数

function randombetween(min, max){
    return min + (Math.random() * (max-min +1));
}
TracerLee commented 7 years ago

总结js常用函数和常用技巧(持续更新)

TracerLee commented 7 years ago

lazyload方案

基于jQuery或Zepto: lazyload.js

TracerLee commented 7 years ago

window load 事件的事件处理程序

语法

window.onload = funcRef;

定义

在文档装载完成后会触发 load 事件。此时,在文档中的所有对象都在DOM中,所有图片,脚本,链接以及子框都完成了装载。

同时也会有 Gecko-指定 DOM事件,如 DOMContentLoaded 和 DOMFrameContentLoaded (它们可以使用 EventTarget.addEventListener() 来处理 ) , 这些事件在页面DOM构建起来后就会触发,而不会等到其他的资源都装载完成。

参考: https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalEventHandlers/onload

TracerLee commented 7 years ago

随机生成字符串

Number.prototype.toString()

Math.random().toString(32).substr(2)

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString

TracerLee commented 7 years ago

获取基于视口的绝对x,y坐标

element.getBoundingClientRect().left
element.getBoundingClientRect().top
TracerLee commented 7 years ago

用正则表达式分析 URL

var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url = "http://harttle.com:80/tags.html?simple=true#HTML",
    result = parse_url.exec(url);
    blanks = '       ';
    fields = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash'];
fields.forEach(function(filed, i){
    console.log(field + ':' + blanks.substr(field.length) + result[i]);
});

输出

url:    http://harttle.com:80/tags.html?simple=true#HTML
scheme: http
slash:  //
host:   harttle.com
port:   80
path:   tags.html
query:  single=true
hash:   HTML

参考: http://harttle.com/2016/02/23/javascript-regular-expressions.html

TracerLee commented 7 years ago

获取对象的属性个数

// 对象
var obj = { a : "foo", b : "bar", c : "baz"};
alert(Object.keys(obj)); // 弹出"a,b,c"
alert(Object.keys(obj).length); // 弹出"3"

参考: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

TracerLee commented 7 years ago

JavaScript错误监听

window.onerror = function (msg, url, lineNo, columnNo, error) {
    var string = msg.toLowerCase();
    var substring = "script error";
    if (string.indexOf(substring) > -1){
        alert('Script Error: See Browser Console for Detail');
    } else {
        alert(msg, url, lineNo, columnNo, error);
    }
  return false;
};

参考: https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalEventHandlers/onerror

TracerLee commented 7 years ago

禁止iframe记录浏览器历史

方案一

通过 replace 来将 url 替换而不是 push 到浏览器历史中。

此方案有个前提条件就是父窗体需要有对iframe窗体的访问权限,因此此方案一般用于iframe载入的内容和父窗体是同域或者同父域的情形。

document.querySeletor('selector').contentWindow.location.replace(url);

方案二

删除iframe节点之后重新创建一个iframe元素。

var oldIframe = document.querySeletor('oldIframe'),
      iframe = document.createElement('iframe');

oldIframe.parentNode.removeChild(oldIframe);
document.body.appendChild(iframe);
iframe.src = url;

参考: http://www.tuicool.com/articles/MzMFJfN

TracerLee commented 7 years ago

深度克隆对象

//对象克隆
function clone(obj){
    if(typeof(obj) != 'object' || obj === null){
        return obj;
    }
    var r = Array.prototype.splice === obj.splice?[]:{};
    for(var i in obj){
        if(obj.hasOwnProperty(i)){
            r[i] = clone(obj[i]);
        }
    }
    return r;
}
TracerLee commented 7 years ago

UMD JavaScript模块写法

https://github.com/umdjs/umd

举个栗子:

// amdWeb.js
// Uses AMD or browser globals to create a module.

// If you want something that will also work in Node, see returnExports.js
// If you want to support other stricter CommonJS environments,
// or if you need to create a circular dependency, see commonJsStrict.js

// Defines a module "amdWeb" that depends on another module called "b".
// Note that the name of the module is implied by the file name. It is best
// if the file name and the exported global have matching names.

// If the 'b' module also uses this type of boilerplate, then
// in the browser, it will create a global .b that is used below.

// If you do not want to support the browser global path, then you
// can remove the `root` use and the passing of `this` as the first arg to
// the top function.

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['b'], factory);
    } else {
        // Browser globals
        root.amdWeb = factory(root.b);
    }
}(this, function (b) {
    //use b in some fashion.

    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return {};
}));
TracerLee commented 6 years ago

HTML 字符实体转换

// HTML 字符实体
// 转换
var htmlStringDeal = (function () {
    var keys = Object.keys || function(obj) {
        obj = Object(obj)
        var arr = []   
        for (var a in obj) arr.push(a)
        return arr
    }
    var invert = function(obj) {
        obj = Object(obj)
        var result = {}
        for (var a in obj) result[obj[a]] = a
        return result
    }
    var entityMap = {
        escape: {
          '&': '&amp;',
          '<': '&lt;',
          '>': '&gt;',
          '"': '&quot;',
          "'": "&apos;"
        }
    }
    entityMap.unescape = invert(entityMap.escape)
    var entityReg = {
        escape: RegExp('[' + keys(entityMap.escape).join('') + ']', 'g'),
        unescape: RegExp('(' + keys(entityMap.unescape).join('|') + ')', 'g')
    }

    return {
        // 将HTML转义为实体
        escape: function (html) {
            if (typeof html !== 'string') return ''
            return html.replace(entityReg.escape, function(match) {
                return entityMap.escape[match]
            })
        },
        // 将实体转回为HTML
        unescape: function (str) {
            if (typeof str !== 'string') return ''
            return str.replace(entityReg.unescape, function(match) {
                return entityMap.unescape[match]
            })   
        } 
    }
})()
TracerLee commented 6 years ago

打开新窗口

// <a href="url">url</a>
// 等同
window.location.href="url";
// <a href="url" target="_blank">url新窗口</a>
// 等同
window.open("url");
TracerLee commented 6 years ago

获取 Issue 页面 Dom 类数组转换成数组,再计算数字总和

eval([...document.querySelectorAll('.text-small.text-bold')].map(v => v.innerHTML).join('+'))
TracerLee commented 6 years ago

转 Unicode

/**
 * String to Unicode, e.g. 安 : \u5b89
 * @param  {String} non-Unicode charset, any character above 0x7e, accept long sentence
 * @return {String} Unicode
 */
exports.s2uni = function (s) {
    var unit2Unicode = function (unit) {return '\\u' + unit.charCodeAt().toString(16)};
    return s.split('').map(unit2Unicode).join('');
}
TracerLee commented 5 years ago

单例倒置模式

$(() => {
  (function init(global, factory) {
    const o = factory();

    o.method();
  }(this, () => ({
    method() {
      console.log('hello world');
    },
  })));
});
TracerLee commented 5 years ago

模块写法

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global.moduleName = factory());
}(this, (function () { 'use strict';
  let moduleName = {};
  return moduleName;
})));
TracerLee commented 5 years ago

使用 JSX 开发需要注意如下几点:

  1. 只能有一个最外层节点,不能同事出现平行的最外层标签(因为createElementa只能创建一个dom节点,其余的是其子节点)
  2. 需要使用“小写字母+中划线”来引用外部组件,例如i-button、dropdown-menu
  3. 如果需要引入vue对象中的data数据,语法是 {this.dataName},例如{this.buttonName}
  4. 如果是希望引入事件,即on-“事件名称”,如果事件名称是驼峰命名,需要使用中划线代替,例如on-on-click,组件定义的是on-click事件,那么在jsx中需要使用on-on-click事件,第一个on相当于原生定义事件的方式。
  5. 事件的引入与变量的引入类似,{this.methodName},例如:{this.test}