1. 程式人生 > >js常用程式碼收集

js常用程式碼收集

1. PC - js

  • 返回指定範圍的隨機數(m-n之間)的公式
Math.random()*(n-m)+m
// event.preventDefault()會阻擋預設要發生的事件.
// event.stopPropagation()會阻擋發生冒泡事件.
// 而return false則是前面兩者的事情他都會做: // 他會做event.preventDefault(); // 他會做event.stopPropagation(); // 停止callback function的執行並且立即return回來
  • 複製文字到剪下板
function copyToClipboard(data) {
    const _tempInput = document.createElement('input') _tempInput.value = data.value document.body.appendChild(_tempInput) _tempInput.select() document.execCommand('Copy') document.body.removeChild(_tempInput) }
  • 前端生成檔案並下載
function createAndDownloadFile(fileName, content) {
    const aTag = document.createElement('a'); const blob = new Blob([content]); aTag.download = `${fileName}.json`; aTag.href = URL.createObjectURL(blob); aTag.click(); URL.revokeObjectURL(blob); }
  • 高亮文字
function highlight(text, words, tag='span') { let i, len = words.length, re; for (i = 0; i < len; i++) { re = new RegExp(words[i], 'g'); if (re.test(text)) { text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>'); } } return text; } 
  • 限制文字字數
function excerpt(str, nwords) {
    let words = str.split(' '); words.splice(nwords, words.length-1); return words.join(' ') + (words.length !== str.split(' ').length ? '…' : ''); }
  • 簡單建立動態選單下拉列表
function createMenu(items, tags=['ul', 'li']) { const parent = tags[0]; const child = tags[1]; let item, value = ''; for (let i = 0, l = items.length; i < l; i++) { item = items[i]; if (/:/.test(item)) { item = items[i].split(':')[0]; value = items[i].split(':')[1]; } items[i] = '<'+ child +' '+ (value && 'value="'+value+'"') +'>'+ item +'</'+ child +'>'; } return '<'+ parent +'>'+ items.join('') +'</'+ parent +'>'; }
  • 防止被Iframe巢狀
if(top != self){
    location.href = ”about:blank”; }
  • 兩種圖片lazy載入的方式 第一個By JS中級交流群 成都-獵巫 第二個By 上海-zenki
// @description 準備為圖片預載入使用的外掛
// 使用的圖片容器css類名為lazy-load-wrap
// 圖片真實地址為data-lazy-src // 當lazy-load-wrap容器進入視口,則開始替換容器內所有需要延遲載入的圖片路徑,並更改容器的載入狀態 //第一種方法 $.fn.compassLazyLoad=function(){ var _HEIGHT=window.innerHeight, _lazyLoadWrap=$('.lazy-load-wrap'); var methods={ setOffsetTop:function(){ $.each(_lazyLoadWrap,function(i,n){ $(n).attr({ 'top':n.offsetTop-_HEIGHT, 'status':'wait' }); }) }, isShow:function(){ var _scrollTop=$(window).scrollTop; //利用image容器判斷是否進入視口,而非image本身 $.each(_lazyLoadWrap,function(){ var _that=$(this); if (_that.attr('status')==='done') { return; }; if (_that.attr('top')<=_scrollTop) { _that.find('img[data-lazy-src]').each(function(i,n){ n.src=$(n).data('lazy-src'); }); _that.attr('status','done'); }; }) }, scroll:function(){ $(window).on('scroll',function(){ methods.isShow(); }); }, init:function(){ methods.setOffsetTop(); methods.isShow(); methods.scroll(); } }; methods.init(); } //第二種方法 var exist=(function($){ var timer=null, temp=[].slice.call($('.container')); ret={}; for(var i=0,len=temp.length-1;i<=len;i++){ ret[i]=temp[i]; } var isExist=function(winTop,winEnd){ for(var i in ret){ console.log(ret); var item=ret[i], eleTop=item.offsetTop, eleEnd=eleTop+item.offsetHeight; if((eleTop>winTop&&eleTop<=winEnd)||(eleEnd>winTop&&eleEnd<=winEnd)){ $(item).css('background','none'); new Tab($(item).attr('id'),data).init; delete ret[i]; } } } return { timer:timer; isExist:isExist; }; })($); //第三種方法 Zepto(function ($) { var swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, autoplay: 3000, loop: true, autoplayDisableOnInteraction: false }); (function lazyLoad() { var imgs = $(".lazyLoad"); var src = ''; $.each(imgs, function (index, item) { src = $(item).attr('data-src'); $(item).attr('src', src); }); })(); }); $(function () { var lazyLoadTimerId = null; /// 智慧載入事件 $(window).bind("scroll", function () { clearTimeout(lazyLoadTimerId); lazyLoadTimerId = setTimeout(function () { // 延遲載入所有圖片 var isHttp = (location.protocol === "http:"); $("#ym_images img").each(function () { var self = $(this); if (self.filter(":above-the-fold").length > 0) { var originUrl = self.attr("data-original"); self.attr("src", originUrl); } }); }, 500); }); }); 
  • 某年某月的1號為星期幾
var weekday = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]; weekday[new Date(2015, 9, 1).getDay()]; //2015年10月1號

2. Mobile - js

var u = navigator.userAgent, app = navigator.appVersion; var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android終端或者uc瀏覽器 var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios終端 alert('是否是Android:'+isAndroid); alert('是否是iOS:'+isiOS);

3. 微信 weixin

  • UserAgent 判斷微信客戶端
// Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12F70 MicroMessenger/6.1.5 NetType/WIFI
function isWechat() {  
    var ua = navigator.userAgent.toLowerCase(); return /micromessenger/i.test(ua) || /windows phone/i.test(ua); }
  • 獲取單個dom元素
function $(selector, el) {
  if (!el) { el = document; } return el.querySelector(selector); }
  • 獲取多個dom元素
function $$(selector, el) {
  if (!el) { el = document; } return el.querySelectorAll(selector); // Note: the returned object is a NodeList. // If you'd like to convert it to a Array for convenience, use this instead: // return Array.prototype.slice.call(el.querySelectorAll(selector)); }
  • 將nodeList集合轉換為陣列
function convertToArray(nodeList) {
  var array = null try { // IE8-NodeList是COM物件 array = Array.prototype.slice.call(nodeList, 0) } catch (err) { array = [] for (var i = 0, len = nodeList.length; i < len; i++) { array.push(nodeList[i]) } } return array }
  • ajax函式
function ajax(setting) {
  //設定引數的初始值
  var opts = { method: (setting.method || "GET").toUpperCase(), //請求方式 url: setting.url || "", // 請求地址 async: setting.async || true, // 是否非同步 dataType: setting.dataType || "json", // 解析方式 data: setting.data || "", // 引數 success: setting.success || function () { }, // 請求成功回撥 error: setting.error || function () { } // 請求失敗回撥 }; // 引數格式化 function params_format(obj) { var str = ""; for (var i in obj) { str += i + "=" + obj[i] + "&"; } return str .split("") .slice(0, -1) .join(""); } // 建立ajax物件 var xhr = new XMLHttpRequest(); // 連線伺服器open(方法GET/POST,請求地址, 非同步傳輸) if (opts.method == "GET") { xhr.open( opts.method, opts.url + "?" + params_format(opts.data), opts.async ); xhr.send(); } else { xhr.open(opts.method, opts.url, opts.async); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(opts.data); } /*  ** 每當readyState改變時,就會觸發onreadystatechange事件  ** readyState屬性儲存有XMLHttpRequest的狀態資訊  ** 0 :請求未初始化  ** 1 :伺服器連線已建立  ** 2 :請求已接受  ** 3 : 請求處理中  ** 4 :請求已完成,且相應就緒  */ xhr.onreadystatechange = function () { if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) { switch (opts.dataType) { case "json": var json = JSON.parse(xhr.responseText); opts.success(json); break; case "xml": opts.success(xhr.responseXML); break; default: opts.success(xhr.responseText); break; } } }; xhr.onerror = function (err) { opts.error(err); }; }
  • JS介面安全域名不填寫,分享onMenuShareAppMessage直接會取預設值。
// 分享onMenuShareAppMessage直接會取預設值
  • 關閉當前頁面
WeixinJSBridge.call('closeWindow');
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady(){ that.initOrder(); }, false);
  • 支付介面方法呼叫必須在
WeixinJSBridge.invoke('getBrandWCPayRequest', d, function(res){ if(res.err_msg == "get_brand_wcpay_request:ok"){ // alert("支付成功"); // union.release(d.orderId); resetUrl(); paySuccess('home', d.orderId); } else { cancelOrder(d.orderId); // alert(res.err_msg); } loading.hide(); });
  • 瀑布流無限載入例項
// be dependent on jquery & jquery.infinitescroll.min.js
// insert this '<div id="more"><a href="api?page="></a></div>' to your page.html
(function($){ $(function(){ var $container = $('.list-wrap-gd'); function layOutCallBack() { $container.imagesLoaded(function(){ $container.masonry({ itemSelector: '.item-bar', gutter: 10 }); }); $container.imagesLoaded().progress( function() { $container.masonry('layout'); }); } layOutCallBack(); $container.infinitescroll({ navSelector : "#more", nextSelector : "#more a", itemSelector : ".item-bar", pixelsFromNavToBottom: 300, loading:{ img: "/images/masonry_loading.gif", msgText: ' ', finishedMsg: "<em>已經到最後一頁</em>", finished: function(){ $("#more").remove(); $("#infscr-loading").hide(); } }, errorCallback:function(){ $(window).unbind('.infscr'); }, pathParse: function (path, nextPage) { var query = ""; var keyword=$("#search_keyword").val(); var cat_id=$("#cat_id").val(); var brand_id=$("#brand_id").val(); var country_id = $("#country_id").val(); query = query + "&namekeyword="+keyword; query = query +"&cat_id="+cat_id query = query + "&brand_id=" + brand_id; query = query + "&country_id=" + country_id; path = [path,query]; return path; } }, function(newElements) { var $newElems = $( newElements ).css({ opacity: 0 }); $newElems.imagesLoaded(function(){ $newElems.animate({ opacity: 1 }); $container.masonry( 'appended', $newElems, true ); layOutCallBack(); }); }); }); })(jQuery);
if( /iPhone|iPod|iPad/i.test(navigator.userAgent) ) { $(document).on('focus', 'input, textarea', function() { $('header').css("position", 'absolute'); $('footer').css("position", 'absolute'); }); $(document).on('blur', 'input, textarea', function() { $('header').css("position", 'fixed'); $('footer').css("position", 'fixed'); }); } 
  • 得到地理位置
function getLocation(callback){
  if(navigator.geolocation){ navigator.geolocation.getCurrentPosition( function(p){ callback(p.coords.latitude, p.coords.longitude); }, function(e){ var msg = e.code + "\n" + e.message; } ); } }
(function(doc, win){
  var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function(){ var clientWidth = docEl.clientWidth; if(!clientWidth) return; docEl.style.fontSize = 20 * (clientWidth / 320) + 'px'; }; if(!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window);
var dpr, rem, scale;
var docEl = document.documentElement;
var fontEl = document.createElement('style'); var metaEl = document.querySelector('meta[name="viewport"]'); dpr = window.devicePixelRatio || 1; rem = docEl.clientWidth * 2 / 10; scale = 1 / dpr; // 設定viewport,進行縮放,達到高清效果 metaEl.setAttribute('content', 'width=' + dpr * docEl.clientWidth + ',initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale + ',user-scalable=no'); // 設定data-dpr屬性,留作的css hack之用 docEl.setAttribute('data-dpr', dpr); // 動態寫入樣式 docEl.firstElementChild.appendChild(fontEl); fontEl.innerHTML = 'html{font-size:' + rem + 'px!important;}'; // 給js呼叫的,某一dpr下rem和px之間的轉換函式 window.rem2px = function(v) { v = parseFloat(v); return v * rem; }; window.px2rem = function(v) { v = parseFloat(v); return v / rem; }; window.dpr = dpr; window.rem = rem;
  • 獲取js所在路徑
function getJsDir (src) {
    var script = null; if (src) { script = [].filter.call(document.scripts, function (v) { return v.src.indexOf(src) !== -1; })[0]; } else { script = document.scripts[document.scripts.length - 1]; } return script ? script.src.substr(0, script.src.lastIndexOf('/')) : script; }
  • 頁面載入自執行函式
function addload(func) {
  var old = window.onload; if (typeof window.onload != "function") { window.onload = func; } else { window.onload = function () { old(); func(); } } }
  • 從全域性捕獲錯誤
window.onerror = function (errMsg, scriptURI, lineNumber, columnNumber, errorObj) { setTimeout(function () { var rst = { "錯誤資訊:": errMsg, "出錯檔案:": scriptURI, "出錯行號:": lineNumber, "出錯列號:": columnNumber, "錯誤詳情:": errorObj }; alert(JSON.stringify(rst, null, 10)); }); };
var $body = $('body'); document.title = 'title'; // hack在微信等webview中無法修改document.title的情況 var $iframe = $('<iframe src="/favicon.ico"></iframe>').on('load', function(){ setTimeout(function(){ $iframe.off('load').remove() }, 0) }).appendTo($body)

1. 常用方法 - js

  • 字串長度擷取
function cutstr(str, len) {
    var temp,
        icount = 0, patrn = /[^\x00-\xff]/, strre = ""; for (var i = 0; i < str.length; i++) { if (icount < len - 1) { temp = str.substr(i, 1); if (patrn.exec(temp) == null) { icount = icount + 1 } else { icount = icount + 2 } strre += temp } else { break; } } return strre + "..." }
  • 替換全部
String.prototype.replaceAll = function(s1, s2) { return this.replace(new RegExp(s1, "gm"), s2) }
  • 清除空格
String.prototype.trim = function() {
    var reExtraSpace = /^\s*(.*?)\s+$/; return this.replace(reExtraSpace, "$1") }
  • 清除左空格/右空格
function ltrim(s){ return s.replace( /^(\s*| *)/, ""); } function rtrim(s){ return s.replace( /(\s*| *)$/, ""); }