1.JavaScript 函數節流
用途:如調整瀏覽器大小,或者用戶輸入信息,致使反覆提交接口javascript
function throttle(method,context) { clearTimeout(method.tId); method.tId=setTimeout(function() { method.call(context); },500); }
調用方法:css
window.onresize = function() { throttle(winResize); }
2.JavaScript判斷手機端訪問html
function isPhone() { var sUserAgent = navigator.userAgent; if (sUserAgent.indexOf('Android') > -1 && sUserAgent.indexOf('Mobile') > -1 ||sUserAgent.indexOf('iPhone') > -1 ||sUserAgent.indexOf('iPod') > -1 || sUserAgent.indexOf('Symbian') > -1 || sUserAgent.indexOf('IEMobile') > -1){ //coding... } }
3.獲取URL地址欄參數java
function GetQueryString(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null)return unescape(r[2]); return null; }
4.jQuery返回頂部jquery
$(function() { //當滾動條的位置處於距頂部100像素如下時,跳轉連接出現,不然消失 $(function () { $(window).scroll(function(){ if ($(window).scrollTop()>100){ $("#back_to_top").fadeIn(1500); } else { $("#back_to_top").fadeOut(1500); } }); //當點擊跳轉連接後,回到頁面頂部位置 $("#back_to_top").click(function(){ $('body,html').animate({scrollTop:0},1000); return false; }); }); });
5.正則檢測手機號,郵箱android
var reg= /^[1][0-9]\d{9}$/; mReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;郵箱 qqReg = /^[1-9][0-9]{4,9}$/ if(!reg.test(mobilephone)||mobilephone == null){ alert("請輸入正確的手機號!"); return false; };
6.生成隨機數函數ios
function getRandom(n){ return Math.floor(Math.random()*n+1) }
1)獲取0-100的隨機數——getRandom(100);web
2)獲取0-999的隨機數——getRandom(999);ajax
7.jQuery模擬鼠標點擊事件json
$("#a").trigger("click");//模擬執行id=a的事件
8.jQuery-onload讓第一次頁面加載時圖片是淡入方式顯示
$("#load img").load(function() { //圖片默認隱藏 $(this).hide(); //使用fadeIn特效 $(this).fadeIn("5000"); }) <div id="load" class="loading"> <img src="images/apple_3_bigger.jpg" style="height:auto"> </div>
9.判斷微信瀏覽器
var ua = navigator.userAgent.toLowerCase(); if(ua.match(/MicroMessenger/i)=="micromessenger") { event.preventDefault(); ... }
10.錨點滑動效果
$('a').click(function(){ $('html, body').animate({ scrollTop: $( $.attr(this, 'href') ).offset().top }, 400); return false; });
11.多行文本溢出顯示省略號
.figcaption { background: #EEE; width: 410px; height: 3em; margin: 1em; } .figcaption p { margin: 0; line-height: 1.5em; } //////css overflow: hidden; display: -webkit-box; -webkit-line-clamp: 5; -webkit-box-orient: vertical; word-break: break-all; <div class="figcaption"><p>固定一個喜歡的網站可不能夠?固然!把天天常去的網站通通固定到開始屏幕中。如何固定?打開 IE10,在網頁空白處點擊鼠標右鍵,在應用欄中點擊「圖釘」圖標便可完成固定。</p></div> $(".figcaption").each(function(i){ var divH = $(this).height(); var $p = $("p", $(this)).eq(0); while ($p.outerHeight() > divH) { $p.text($p.text().replace(/(\s)*([a-zA-Z0-9]+|\W)(\.\.\.)?$/, "...")); }; });
12.倒計時
var lastTime = 0; // 剩餘時間 (秒) var Timer = null function calTime(){ if(lastTime <= 0){ clearTimeout(Timer); $leftTime.html('已超時'); return false; } var minute = parseInt(lastTime / 60, 10); var second = lastTime%60; var mm = minute<10 ? ('0'+minute) : minute; var ss = second<10 ? ('0'+second) : second; $leftTime.html(mm +'分'+ss+'秒'); lastTime--; setTimeout(function(){ calTime(); },1000) } var $leftTime = $('#leftTime'); if($leftTime.length){ lastTime = Number($('#leftTime').data('resttime')); Timer = setTimeout(function(){ calTime(); },1000); }
13.點擊發送驗證碼倒計時
//倒計時60s var wait=60; function time(o) { console.log(o); if (wait == 0) { o.removeAttr("disabled"); o.val("免費獲取驗證碼"); wait = 60; } else { o.attr("disabled", true); o.val("從新發送(" + wait + ")"); wait--; setTimeout(function() { time(o) }, 1000) } } <input type="button" id="gain_code" value="獲取短信驗證碼" class="gain-code">
14.jquery 彈出層
dom: <div id="bg"></div> <div class="pop">彈窗內容</div> #bg { background-color: #000; position: absolute; z-index: 99; left: 0; top: 0; display: none; width: 100%; height: 100%; opacity: 0.9; filter: alpha(opacity=90); -moz-opacity: 0.9; } js: $("ele").click(function () { if($("#bg").length != 1){ $(".footer").after(tpl); } $(window).scroll(function(){ if ($(window).scrollTop()>20){ $('body,html').animate({scrollTop:0},100); return false; } }); var $box = $('.pop-box'); $box.css({ //設置彈出層距離左邊的位置 left: ($("body").width() - $box.width()) / 2 + "px", //設置彈出層距離上面的位置 top: "0px", /*top: ($(window).height() - $box.height()) / 2 + $(window).scrollTop() + "px",*/ display: "block" }); }); //點擊關閉按鈕的時候,遮罩層關閉 $(".container").on('click', '.close', function(event) { event.preventDefault(); $("#bg,.pop-box").remove(); });
//點擊彈窗以外部分隱藏 $(document).click(function(event) { var _con = $(".pop"); if(!_con.is(event.target) && _con.has(event.target).length === 0){ // Mark 1 $(".pop").hide(); } });
15.javascript cookie操做
//設置cookie function setCookie(cookieName,cookieValue,cookieExpires,cookiePath) { cookieValue = escape(cookieValue);//編碼latin-1 if(cookieExpires=="") { var nowDate = new Date(); nowDate.setMonth(nowDate.getMonth()+6); cookieExpires = nowDate.toGMTString(); } if(cookiePath!="") { cookiePath = ";Path="+cookiePath; } document.cookie= cookieName+"="+cookieValue+";expires="+cookieExpires+cookiePath; } //獲取cookie function getCookieValue(cookieName) { var cookieValue = document.cookie; var cookieStartAt = cookieValue.indexOf(""+cookieName+"="); if(cookieStartAt==-1) { cookieStartAt = cookieValue.indexOf(cookieName+"="); } if(cookieStartAt==-1) { cookieValue = null; } else { cookieStartAt = cookieValue.indexOf("=",cookieStartAt)+1; cookieEndAt = cookieValue.indexOf(";",cookieStartAt); if(cookieEndAt==-1) { cookieEndAt = cookieValue.length; } cookieValue = unescape(cookieValue.substring(cookieStartAt,cookieEndAt));//解碼latin-1 } return cookieValue; }
16.頁面初始化漸變
<script language="javascript" type="text/javascript"> $(document).ready(function(){ $("body").css("display","none"); $("body").fadeIn(2000); //這個值,本身根據須要設定 }); </script>
17.用iframe模擬ajax上傳文件
1.<form method="post" action="xxx" enctype="multipart/form-data" id="picSubmit" target="form_iframe"></form> //這裏是重點。要上傳文件enctype這個屬性不可少,target的值改成iframe的name的值。 2.<iframe id="form_iframe" name="form_iframe" style="display:none;"> </iframe> 3.Response.Write("<script type='text/javascript' type='language'>parent.window.callBackMethod('上傳失敗'); //服務端返回js代碼以及狀態碼 //parent.window.uploadSuccess(); //這個是JS調用父頁的方法 4.js var uploadSuccess = function(data){ if(data){ var str = data; var statue = str.split(",")[0], statue1 = str.split(",")[1]; if(statue == 1){ alert("上傳成功!"); }else{ alert(statue1); } } } //前提必須同域
老虎機自定義中止位置
插件裏沒發現有這個參數,不過能夠簡單修改一下插件達到這個效果。
$.each(data, function(index, val) { if (val.areaid == 2) { var areaTpl = '<p id="{sever_id}">{server_list}</p>', areaItem = [], areaList = data[0].server_list; $.each(val.server_list, function(index, val) { var areaStr = areaTpl.replace(/\{server_list\}/gi, val.name) .replace(/\{sever_id\}/gi, val.id); areaItem.push(areaStr); }); $area.append(areaItem); } });
$("#ios").click(function(event) { var ua = navigator.userAgent.toLowerCase(); if(ua.match(/MicroMessenger/i)=="micromessenger") { blockShow(); event.preventDefault(); } });
if(navigator.userAgent.indexOf("MSIE")>0){ if(navigator.userAgent.indexOf("MSIE 9.0")>0 || navigator.userAgent.indexOf("MSIE 8.0")>0 || navigator.userAgent.indexOf("MSIE 7.0")>0 || navigator.userAgent.indexOf("MSIE 6.0")>0){ $("#slotMachineButton1").hide(); $("#slot_ie").show(); } }
<embed src="http://9yinsy.woniu.com/static/act/201605/gsws/media/banner.swf" autostart="true" loop="loop" width="100%" height="900px" wmode="Opaque" class="embed"/>
(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 = clientWidth / 7.5 + 'px'; //等價於clientWidth / 750 * 100 + 'px'; }; if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false);//resize doc.addEventListener('DOMContentLoaded', recalc, false);//reload })(document, window);
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) { var loadDateTime = new Date(); window.setTimeout(function() { var timeOutDateTime = new Date(); if (timeOutDateTime - loadDateTime < 5000) { window.location = "http://gwact.woniu.com/api/channel/358"; } else { window.close(); } }, 25); window.location = 'wnapp://'; } else if (navigator.userAgent.match(/android/i)) { var state = null; try { state = window.open('wnapp://', '_blank'); } catch(e) {} if (state) { window.close(); } else { window.location = "http://gwact.woniu.com/api/channel/358"; } }
h5視頻播放,暫停
$("#media").get(0).play(); $("#media").get(0).pause();
<!DOCTYPE html> <html> <head> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> var countdown=60; function settime(obj) { if (countdown == 0) { obj.removeAttribute("disabled"); obj.value="免費獲取驗證碼"; countdown = 60; return; } else { obj.setAttribute("disabled", true); obj.value="從新發送(" + countdown + ")"; countdown--; } setTimeout(function() { settime(obj) } ,1000) } </script> <body> <input type="button" id="btn" value="免費獲取驗證碼" onclick="settime(this)" /> </body> </html>
iframe判斷手機是否安裝app,安裝打開,未安裝下載
function show(){ if( navigator.userAgent.indexOf('MicroMessenger') != -1 ){ document.getElementById("openBrowser").style.display = "block"; }else{ } } function clik(){ 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終端 var isIpad = u.indexOf('iPad') > -1; //是否iPad var isIPhone = u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1; //是否爲iPhone或者QQHD瀏覽器 if(isAndroid){ var ifrSrc = "jsmcc://H/5"+"?json={'urlorClass':'http://wap.js.10086.cn/activity/482','type':'0','description':'0','isLogin':'1','title':'升級4G,抱走6GB超大流量','isurlComplete':'0','isShare':'0'}"; //使用iframe方式觸發jsmcc:// var ifr = document.createElement('iframe'); ifr.src = ifrSrc ; ifr.style.display = 'none'; document.body.appendChild(ifr); //當iframe加載5秒後,不管是否能切換到APP窗口(未安裝或者版本不對,是不會打開APP的),頁面繼續跳轉 setTimeout( function(){ window.location.href="http://wap.js.10086.cn/userfiles/wapapp/jsmcc.apk"; //固然也能夠回退到前一頁面 //window.history.go(-1); },3000); }else if(isIOS || isIpad || isIPhone){ var ifrSrc = "jsmcc://H/5"+"?json={'urlorClass':'http://wap.js.10086.cn/activity/482','type':'0','description':'0','isLogin':'1','title':'升級4G,抱走6GB超大流量','isurlComplete':'0','isShare':'0'}"; //使用iframe方式觸發jsmcc:// var ifr = document.createElement('iframe'); window.location = ifrSrc ; ifr.style.display = 'none'; document.body.appendChild(ifr); //當iframe加載5秒後,不管是否能切換到APP窗口(未安裝或者版本不對,是不會打開APP的),頁面繼續跳轉 setTimeout( function(){ window.location.href="https://itunes.apple.com/cn/app/id446332125?mt=8&t"; //固然也能夠回退到前一頁面 //window.history.go(-1); },3000); }else{ //電腦端 不作處理 } }
// 字符串乘法 String.prototype.times = function(n) { return Array.prototype.join.call({length:n+1}, this); }; "*".times(5) => *****
var worker; function startWorker(){ if(typeof(Worker)!=="undefined"){ // if(typeof(worker)=="undefined"){ // } //比較重要的js,單獨放置 worker = new Worker("./js/countdown.js"); worker.onmessage = function (event) { }; } else{ } } //銷燬 function stopWorker(){ worker.terminate(); }
// 判斷瀏覽器是否支持placeholder
var isPlaceholer = function(){ var input = document.createElement('input'); return "placeholder" in input; } var editPlaceholder = function(){ var $phone = $('.phone'); if (!isPlaceholer()) { $phone.val('請輸入正確的手機號碼'); $phone.focus(function(event) { var msg = $phone.val(); if (msg == '請輸入正確的手機號碼') { $phone.val(''); } }); $phone.blur(function(event) { var msg = $phone.val(); if (msg == '') { $phone.val('請輸入正確的手機號碼'); } }); } };