Open TracerLee opened 8 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);
}
location.hash = '';
location.hash = 'anchor';
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, " "));
}
$(selector).on('touchmove', function (e) {
e.preventDefault();
});
.ovfHiden{overflow: hidden;height: 100%;}
$('html,body').addClass('ovfHiden'); //使网页不可滚动
$('html,body').removeClass('ovfHiden'); //使网页恢复可滚动
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) { }
}
}
添加和修改历史记录条目
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事件中被修改。
参考资料:
手机号验证
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])$/;
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 '';
};
function randombetween(min, max){
return min + (Math.random() * (max-min +1));
}
基于jQuery或Zepto: lazyload.js
window.onload = funcRef;
在文档装载完成后会触发 load 事件。此时,在文档中的所有对象都在DOM中,所有图片,脚本,链接以及子框都完成了装载。
同时也会有 Gecko-指定 DOM事件,如 DOMContentLoaded 和 DOMFrameContentLoaded (它们可以使用 EventTarget.addEventListener() 来处理 ) , 这些事件在页面DOM构建起来后就会触发,而不会等到其他的资源都装载完成。
参考: https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalEventHandlers/onload
Number.prototype.toString()
Math.random().toString(32).substr(2)
参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
element.getBoundingClientRect().left
element.getBoundingClientRect().top
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
// 对象
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
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
通过 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;
//对象克隆
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;
}
举个栗子:
// 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 {};
}));
// 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: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": "'"
}
}
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]
})
}
}
})()
// <a href="url">url</a>
// 等同
window.location.href="url";
// <a href="url" target="_blank">url新窗口</a>
// 等同
window.open("url");
eval([...document.querySelectorAll('.text-small.text-bold')].map(v => v.innerHTML).join('+'))
/**
* 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('');
}
$(() => {
(function init(global, factory) {
const o = factory();
o.method();
}(this, () => ({
method() {
console.log('hello world');
},
})));
});
(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;
})));
使用 JSX 开发需要注意如下几点:
Javascript代码片段收集