1.JavaScript 函数节流
用途:如调整浏览器大小,或者用户输入信息,导致反复提交接口
function throttle(method,context) {
clearTimeout(method.tId);
method.tId=setTimeout(function() {
method.call(context);
},500);
}
调用方法:
window.onresize = function() {
throttle(winResize);
}
2.JavaScript判断手机端访问
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地址栏参数
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返回顶部
$(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.正则检测手机号,邮箱
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.生成随机数函数
function getRandom(n){
return Math.floor(Math.random()*n+1)
}
1)获取0-100的随机数——getRandom(100);
2)获取0-999的随机数——getRandom(999);
7.jQuery模拟鼠标点击事件
$("#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);
}
}
}
//前提必须同域
老虎机自定义停止位置
插件里没发现有这个参数,不过可以简单修改一下插件达到这个效果。
18.$.each
$.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);
}
});
19判断微信浏览器打开
$("#ios").click(function(event) {
var ua = navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i)=="micromessenger") {
blockShow();
event.preventDefault();
}
});
20.判断ie浏览器
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();
}
}
21.swf文件嵌入网页
<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"/>
22.移动端rem布局头部
(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);
23.移动网页打开app
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();
jq发送短信验证码60s倒计时
<!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{
//电脑端 不做处理
}
}
js字符串乘法
// 字符串乘法
String.prototype.times = function(n) {
return Array.prototype.join.call({length:n+1}, this);
};
"*".times(5) => *****
JavaScript多线程
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('请输入正确的手机号码');
}
});
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。