-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Javascript小代码 #8
Comments
按钮快速点击/**
* 阻止按钮快速点击,默认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);
} |
JQuery Free
|
Javascript控制锚点跳转location.hash = '';
location.hash = 'anchor'; |
获取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, " "));
} |
移动端禁止滑动$(selector).on('touchmove', function (e) {
e.preventDefault();
}); PC端禁止滑动.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");
参考资料: |
常用正则手机号验证 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])$/; |
操作cookiefunction 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));
} |
lazyload方案基于jQuery或Zepto: lazyload.js |
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 |
随机生成字符串
Math.random().toString(32).substr(2) 参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString |
获取基于视口的绝对x,y坐标element.getBoundingClientRect().left
element.getBoundingClientRect().top |
用正则表达式分析 URLvar 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 |
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 |
禁止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; |
深度克隆对象//对象克隆
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;
} |
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 {};
})); |
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: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": "'"
}
}
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"); |
获取 Issue 页面 Dom 类数组转换成数组,再计算数字总和eval([...document.querySelectorAll('.text-small.text-bold')].map(v => v.innerHTML).join('+')) |
转 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('');
} |
单例倒置模式$(() => {
(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代码片段收集
The text was updated successfully, but these errors were encountered: