当前位置:

可复用的JS/jQuery代码片段

本文最后更新于2014-08-13,已超过 1年没有更新,如果文章内容、图片或者下载资源失效,请留言反馈,我会及时处理,谢谢!

温馨提示:本文共12519个字,读完预计32分钟。

本篇将会不间断整理出一些平时自己常用的js/jQuery代码片段,仅供参考学习。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
/**
 * cookie操作
*  设置cookie的方法为:cookie.set(key,val,day);
 * 获取cookie的方法为:cookie.get(key);
 * 删除cookie的方法为:cookie.del(key);
* */
var cookie = {
	set: function(key,val,day){ // 设置cookie方法
		var date = new Date(); // 获取当前时间
		if(typeof day === 'undefined'){ day = 1} ;
		date.setTime(date.getTime() + day*24*3600*1000); // 格式化为cookie识别的时间
		document.cookie = key + "=" + escape(val) +";expires=" + date.toGMTString() + ";path=/"; // 设置cookie
	},
	get: function(key){ // 获取cookie方法
		var getCookie = document.cookie.replace(/[ ]/g,""); // 获取cookie,并且将获得的cookie格式化,去掉空格字符
		var arrCookie = getCookie.split(";"); // 将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中
		var tips; // 声明变量tips
		for(var i=0;i<arrCookie.length;i++){  // 使用for循环查找cookie中的tips变量
			var arr = arrCookie[i].split("="); // 将单条cookie用"等号"为标识,将单条cookie保存为arr数组
			if(key == arr[0]){  // 匹配变量名称,其中arr[0]是指的cookie名称,如果该条变量为tips则执行判断语句中的赋值操作
				tips = unescape(arr[1]); // 将cookie的值赋给变量tips
				break; // 终止for循环遍历
			}
		}
		return tips;
	},
	del: function(key){ // 删除cookie方法
		var date = new Date();
		date.setTime(date.getTime() - 1*24*3600*1000); // 设置为前一天的时间
		if(this.get(key) != null) document.cookie= key + "="+ this.get(key) +";expires="+date.toGMTString() + ";path=/";
	}
};
 
//检测是否支持fixed
function isSupportFixed() {
    var userAgent = window.navigator.userAgent, 
        ios = userAgent.match(/(iPad|iPhone|iPod)\s+OS\s([\d_\.]+)/),
        ios5below = ios && ios[2] && (parseInt(ios[2].replace(/_/g, '.'), 10) < 5),
        operaMini = /Opera Mini/i.test(userAgent),
        body = document.body,
        div, isFixed;
 
    div = document.createElement('div');
    div.style.cssText = 'display:none;position:fixed;z-index:100;';
    body.appendChild(div);
    isFixed = window.getComputedStyle(div).position != 'fixed';
    body.removeChild(div);
    div = null;
 
    return !!(isFixed || ios5below || operaMini);
}
 
//快速排序
var quickSort = function(arr) {
    if (arr.length <= 1) { return arr; }
    var pivotIndex = Math.floor(arr.length / 2);   //基准位置(理论上可任意选取)
    var pivot = arr.splice(pivotIndex, 1)[0];  //基准数
    var left = [];
    var right = [];
    for (var i = 0; i < arr.length; i++){
        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }
    }
    return quickSort(left).concat([pivot], quickSort(right));  //链接左数组、基准数构成的数组、右数组
};
 
//检测离开网页时 保存数据
$(window).on('beforeunload', function(e) {
        e = e || window.event; //此方法为了在firefox中的兼容
        if (e) {
            e.returnValue = 'haibao want to leave?'; // For IE and Firefox prior to version 4
        }
        return '您的内容尚未保存,确定要离开此页吗?';
});
 
// Ctrl+Enter快捷键操作
function ctrlEnter(event){
    event = event || window.event;
    var keycode = event.keyCode || event.which;
    if (event.ctrlKey && keycode == 13){
        event.preventDefault();
        event.returnValue = false;
        study.sendCon();
    }
}
 
//动态加载js
function loadScript(url, callback){
    var script = document.createElement ("script") ;
   script.type = "text/javascript";
 
    if (script.readyState){ //IE
       script.onreadystatechange = function(){
         if (script.readyState == "loaded" || script.readyState == "complete"){
           script.onreadystatechange = null;
           callback(); 
          }
       };
     } 
     else { //Others
       script.onload = function(){ callback();
     }; 
   }
   script.src = url;
   document.getElementsByTagName("head")[0].appendChild(script); 
 }
 
loadScript("file1.js", function(){  //调用
    alert("File is loaded!"); 
});
 
// 全屏
(function(a, b) {
    "use strict";
    var c = function() {
        var a = [
            ["requestFullscreen", "exitFullscreen", "fullscreenchange", "fullscreen", "fullscreenElement"],
            ["webkitRequestFullScreen", "webkitCancelFullScreen", "webkitfullscreenchange", "webkitIsFullScreen", "webkitCurrentFullScreenElement"],
            ["mozRequestFullScreen", "mozCancelFullScreen", "mozfullscreenchange", "mozFullScreen", "mozFullScreenElement"]
        ];
        for (var c = 0,
                 d = a.length; c < d; c++) {
            var e = a[c];
            if (e[1] in b) return e
        }
    }();
    if (!c) return a.screenfull = !1;
    var d = "ALLOW_KEYBOARD_INPUT" in Element,
        e = {
            init: function() {
                return b.addEventListener(c[2],
                    function(a) {
                        e.isFullscreen = b[c[3]],
                            e.element = b[c[4]],
                            e.onchange(a)
                    }),
                    this
            },
            isFullscreen: b[c[3]],
            element: b[c[4]],
            request: function(a) {
 
                a = a || b.documentElement,
                    a[c[0]](d && Element.ALLOW_KEYBOARD_INPUT),
                b.isFullscreen || a[c[0]]();
            },
            exit: function() {
                b[c[1]]()
            },
            toggle: function(a) {
                this.isFullscreen ? this.exit() : this.request(a)
            },
            onchange: function() {}
        };
    a.screenfull = e.init()
})(window, document);
 
// 判断是否为全屏
function checkFull() {
    var isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;
    if (isFull === undefined) isFull = false;
    return isFull;
}
 
// 检测用户是否浏览当前页
function pageActiveEvent() {
    var hiddenProperty = 'hidden' in document ? 'hidden' :
        'webkitHidden' in document ? 'webkitHidden' :
            'mozHidden' in document ? 'mozHidden' :
                null;
    var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
 
    var onVisibilityChange = function() {
        if (!document[hiddenProperty]) {
            study.lastTime = new Date(); // 使用新的时间戳
        } else {
            study.totalTime += (new Date() - study.lastTime);
        }
    };
    document.addEventListener(visibilityChangeEvent, onVisibilityChange);
}
 
//格式化日期
function getFormatDate(d){
	d = new Date(d);
	var year = d.getFullYear(), month = d.getMonth() + 1, strDate = d.getDate();
	if (month >= 1 && month <= 9) month = "0" + month;
	if (strDate >= 0 && strDate <= 9) strDate = "0" + strDate;
	return year + '/' + month + '/' + strDate;
}
 
/**
* 将时间戳 格式化成日期
* @param format 时间格式
* @returns {string}    返回格式化后的时间
*/
Date.prototype.format = function(format) {
   var date = {
      "M+": this.getMonth() + 1,
      "d+": this.getDate(),
      "h+": this.getHours(),
      "m+": this.getMinutes(),
      "s+": this.getSeconds(),
      "q+": Math.floor((this.getMonth() + 3) / 3),
      "S+": this.getMilliseconds()
   };
   if (/(y+)/i.test(format)) {
      format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
   }
   for (var k in date) {
      if (new RegExp("(" + k + ")").test(format)) {
             format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
      }
   }
   return format;
}
 
/**
 * 获取多久之前
 * @param date  日期
 * @returns {*}     返回多久之前 字符串
 */
function get_howLongAgo(date) {
    var now = new Date();
    var target_date = new Date(date.replace(/-/g, '/'));
    var s1 = now.getTime(), s2 = target_date.getTime();
    var total = (s1 - s2) / 1000;
    var day = parseInt(total / (24 * 60 * 60)); // 计算整数天数
    var afterDay = total - day * 24 * 60 * 60;  // 取得算出天数后剩余的秒数
    var hour = parseInt(afterDay / (60 * 60));  // 计算整数小时数
    var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60;  // 取得算出小时数后剩余的秒数
    var min = parseInt(afterHour / 60);         // 计算整数分
    var afterMin = parseInt(total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);    // 取得算出分后剩余的秒数
    var str;
    if (day >= 1 && day <= 3) {
        str = day + "天前";
    } else if (day > 3) {
        str = new Date(s2).format("yyyy-MM-dd"); //大于3天显示具体日期
    } else if (hour >= 1) {
        str = hour + "小时前";
    } else if (min >= 1) {
        str = min + "分钟前";
    } else {
        str = isNaN(afterMin) ? '刚刚' : (afterMin <= 0 ? '刚刚' : afterMin + "秒前");
    }
    return str;
}
 
//获取格式化的时间
var temp = new Date();
var regex = /\//g;
  (temp.toLocaleDateString() + ' ' + temp.toLocaleTimeString().slice(2)).replace(regex,'-');
 
/**
 * 生成随机数【n - 生成的位数】
 */
function generateMixed(n) {
    var res = "",
        chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    for (var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += chars[id];
    }
    return res;
}
 
 
//手机号中间4位星号代替
function replace_mobile(mobile,front_len,end_len){
	var symbol = '', mobile_len = mobile.length;
	var len = mobile_len - front_len - end_len;
	for(var i=0; i<len; i++) {  symbol += '*'; }
	return mobile.substr(0,front_len) + symbol + mobile.substr(mobile_len-end_len);
}
 
// 星级加载
function userStar(star) {
	var fullStar = Math.floor(star / 2), halfStar = star % 2, returnImg = "", n = 0;
	for (var i = 0; i < fullStar; i++) {
		returnImg += "<img src='../../common/img/star.png' />"; n++; // 加载完整星级
	}
	if (halfStar != 0) {
		returnImg += "<img src='../../common/img/half_star.png' />"; n++; // 加载半颗星级
	}
	for (var j = 0; j < 5 - n; j++) {
		returnImg += "<img src='../../common/img/star_no.png' />";
	}
	return returnImg;
}
 
// 点击空白区域 重置主题评论区
$(document).click(function(event){
     event = event || window.event;
     var _con = $('.commentArea'); // 设置要排除的目标区域
     if(!_con.is(event.target) && _con.has(event.target).length === 0){
         //todo
     }
});
 
// 无缝滚动
var $timer = null;
function marquee(obj, _speed) {                                              
   var top = 0, margintop;
   var lineHeight = 70;
   $timer = setInterval(function() {            
        top++;
        margintop = 0-top;
        obj.find("ul").animate({
             marginTop: margintop
        },0,function() {
            var s = Math.abs(parseInt($(this).css("margin-top")));                                
            if(s >= lineHeight) {
                 top = 0;
                 $(this).css("margin-top", 0); //确保每次都是从0开始,避免抖动
                 $(this).find("li").slice(0, 1).appendTo($(this));                
            }
         });                        
   }, _speed);
}
marquee($('.live-notice'), 40); //demo
 
// 获取url参数
function GetRequest(isencode) {
	var url = location.search; // 获取url中"?"符后的字串
	if(isencode != undefined && isencode == 1){ //解决中文乱码
		url = decodeURI(location.search);
	}
	var theRequest = {};
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
		strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
		}
	}
	return theRequest;
}
 
 
//显示提示框
/**
 * 公用 小提示
 * @return {String} txt: 提示文案
 */
 
css:
/*toast*/
.toast-box{position: fixed; top: 10px; left: 50%; -webkit-transform: translate(-50%, 0); -moz-transform: translate(-50%, 0); -ms-transform: translate(-50%, 0); -o-transform: translate(-50%, 0); transform: translate(-50%, 0); z-index: 99999;}
.toast-box p{padding: 5px 20px; background-color: rgba(0,0,0,.8); color: #fff; text-align: center; border-radius: 4px; font-size: .95rem; margin-bottom: 10px;}
.toast-box p.success{background-color: #1fd19f;}
/*animation*/
.animated{-webkit-animation-duration: 1s;animation-duration: 1s;-webkit-animation-fill-mode: both;animation-fill-mode: both;}
@-webkit-keyframes fadeInDown{from{opacity: 0; -webkit-transform: translate3d(0, -100%, 0); transform: translate3d(0, -100%, 0);} to{opacity: 1; -webkit-transform: none; transform: none;}}
@keyframes fadeInDown{from{opacity: 0; -webkit-transform: translate3d(0, -100%, 0); transform: translate3d(0, -100%, 0);} to{opacity: 1; -webkit-transform: none; transform: none;}}
.fadeInDown{-webkit-animation-name: fadeInDown; animation-name: fadeInDown;}
@-webkit-keyframes fadeOutUp{from{opacity: 1;} to{opacity: 0; -webkit-transform: translate3d(0, -100%, 0); transform: translate3d(0, -100%, 0);}}
@keyframes fadeOutUp{from{opacity: 1;} to{opacity: 0; -webkit-transform: translate3d(0, -100%, 0); transform: translate3d(0, -100%, 0);}}
.fadeOutUp{-webkit-animation-name: fadeOutUp; animation-name: fadeOutUp;}
 
js:
var toast_index = 0;
function toast(txt, type) {
    var $body = $("body");
    var toastLen = $body.find(".toast-box").length;
    toast_index++;
    toastLen == 0 && $body.append("<div class='toast-box'></div>");
    $(".toast-box").prepend('<p class="animated fadeInDown toast' + toast_index + ' '+ (type || "") +'">' + (txt || "出错咯") + '</p>');
    var prevToast = $(".toast" + toast_index);
    setTimeout(function() {
        prevToast.removeClass("fadeInDown").addClass("fadeOutUp");
        setTimeout(function() {
            prevToast.remove();
        }, 1000);
    }, 3000);
}
 
// 过滤html标签
function removeHTMLTag(str) {
	str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
	str = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
	str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
	str = str.replace(/ /ig,'');//去掉
	str = str.replace(/\s+/g,"");
	return str;
}
 
// 数组去重
function unique(arr) {
	var result = [], hash = {};
	for (var i = 0, elem; (elem = arr[i]) != null; i++) {
		if (!hash[elem]) {
			result.push(elem);
			hash[elem] = true;
		}
	}
	return result;
}
 
//判断是否设备系统
function isIosOrAndroid(){
	var u = navigator.userAgent,isAndroid,isiOS,app;
	isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
	isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
	if(isAndroid) app = 1;
	if(isiOS) app = 2;
	return app;
}
 
// 去前后空格
function trim(str) {
    if (str && typeof str === "string") {
        return str.replace(/(^\s*)|(\s*)$/g,""); //去除前后空白符
    }
}
 
// 横竖屏 --解决方案1
var updateOrientation = function(){ if(window.orientation=='-90' || window.orientation=='90') alert('为了更好的体验,请您将手机竖过来看吧'); };
window.onorientationchange = updateOrientation;
 
// 横竖屏 --解决方案2 【推荐】
function detectOrient() {
    var storage = localStorage;
    var data = storage.getItem('J-recordOrientX');
    var w = document.documentElement.clientWidth,
        h = document.documentElement.clientHeight;
    var _Width = 0,
        _Height = 0;
    if(!data) {
        _Width = window.screen.width;
        _Height = window.screen.height;
        storage.setItem('J-recordOrientX',_Width + ',' + _Height);
    }else {
        var str = data.split(',');
        _Width = str[0];
        _Height = str[1];
    }
    if(w == _Width) {
        // 竖屏
        return;
    }
    if(w == _Height){
        // 横屏
        return;
    }
}
detectOrient();
window.addEventListener('resize',detectOrient);
 
//是否横屏竖屏
// Find matches
var mql = window.matchMedia("(orientation: portrait)");
 
// If there are matches, we're in portrait
if(mql.matches) {  
    // Portrait orientation
} else {  
    // Landscape orientation
}
 
// Add a media query change listener
mql.addListener(function(m) {
    if(m.matches) {
        // Changed to portrait
    }
    else {
        // Changed to landscape
    }
});
 
// 点击空白处也能关闭下拉菜单
function downMenu(clickClass,dropMenu){
        $(clickClass).click(function(event){
            event=event||window.event;
            event.stopPropagation();
            $(dropMenu).toggle();
        });
        $(dropMenu).click(function(){
            $(dropMenu).toggle();
        });
        $(document).click(function(e){
            $(dropMenu).hide();
        });
}
 
// 预先载入图像
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)
 
// 部分页面刷新
setInterval(function() {
	$("#refresh").load(location.href+" #refresh>*","");
}, 10000);
 
// 禁用页面的右键菜单
$(document).ready(function(){
     $(document).bind("contextmenu",function(e){
         return false;
     });
});
 
// 获取鼠标位置
$(document).ready(function(){
     $(document).mouseover(function(){
        $('#xy').html("x:"+e.pageX+",y:"+e.pageY);
     });
});
 
// 判断元素是否存在
$(document).ready(function(){
     if($('#id').length){
        //do something
     }
});
 
// 设置div在屏幕中央
$(document).ready(function(){
     jQuery.fn.center = function(){
        this.css('position','absolute')
.css('top',($(window).height() - this.height())/2 + $(window).scrollTop()+'px')
.css('left',($(window).width() - this.width())/2 + $(window).scrollLeft()+'px');
        return this;
     }
 
     //use 
     $('#xy').center();
});
 
// 关闭所有动画效果
$(document).ready(function(){
    jQuery.fx.off = true;
});
 
// 检测鼠标的左键还是右键
$(document).ready(function(){
     $('#xy').mousedown(function(e){
         alert(e.which);  //1=鼠标左键 ,2=鼠标中键,3=鼠标右键
     });
});
 
// 回车提交表单
$(document).ready(function(){
    $('input').keyup(function(e){
       if(e.which=='13'){
           alert('回车提交');
       }
    });
});
 
// 设置全局Ajax参数
$('#load').ajaxStart(function(){
    showLoading(); //显示loading
    disableButtons(); //禁用按钮
});
 
$('#load').ajaxComplete(function(){
    hideLoading(); //隐藏loading
    enableButtons(); //启用按钮
});
 
// 只允许输入数字
<input style="ime-mode:Disabled" onkeyup="value=value.replace(/[^\d]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))" type="text" value=""/>
 
// Open external link in New Window
$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});
 
// Make Everything Mobile Friendly
var scr = document.createElement('script');
scr.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/
jquery.min.js');
document.body.appendChild(scr);
 
scr.onload = function(){
 
	$('div').attr('class', '').attr('id', '').css({
		'margin' : 0,
		'padding' : 0,
		'width': '100%',
		'clear':'both'
	});
};
 
// Image Resize Using jQuery
$(window).bind("load", function() {
	// IMAGE RESIZE
	$('#product_cat_list img').each(function() {
		var maxWidth = 120;
		var maxHeight = 120;
		var ratio = 0;
		var width = $(this).width();
		var height = $(this).height();
 
		if(width > maxWidth){
			ratio = maxWidth / width;
			$(this).css("width", maxWidth);
			$(this).css("height", height * ratio);
			height = height * ratio;
		}
		var width = $(this).width();
		var height = $(this).height();
		if(height > maxHeight){
			ratio = maxHeight / height;
			$(this).css("height", maxHeight);
			$(this).css("width", width * ratio);
			width = width * ratio;
		}
	});
	//$("#contentpage img").show();
	// IMAGE RESIZE
});
 
// Smooth Scrolling
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
 && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
 
// Window load event with minimum delay
(function fn() {
 
  fn.now = +new Date;
 
  $(window).load(function() {
 
     if (+new Date - fn.now < 500) setTimeout(fn, 500);
 
		 // Do something...
 
  });
 
})();
 
// jQuery Accordion
(function($) {
 
  var allPanels = $('.accordion > dd').hide();
 
  $('.accordion > dt > a').click(function() {
    allPanels.slideUp();
    $(this).parent().next().slideDown();
    return false;
  });
 
})(jQuery);
 
// Scroll Page Horizontally With Mouse Wheel
$(function() {
 
   $("body").mousewheel(function(event, delta) {
 
      this.scrollLeft -= (delta * 30);
 
      event.preventDefault();
 
   });
 
});
 
// Better Broken Image Handling
// Replace source
$('img').error(function(){
        $(this).attr('src', 'missing.png');
        //$(this).hide(); // Or, hide them
});
 
// Load Content on Scroll Automatically
var loading = false;
$(window).scroll(function(){
	if((($(window).scrollTop()+$(window).height())+250)>=$(document).
height()){
		if(loading == false){
			loading = true;
			$('#loadingbar').css("display","block");
			$.get("load.php?start="+$('#loaded_max').val(), 
function(loaded){
				$('body').append(loaded);
				$('#loaded_max').val(parseInt($('#loaded_max')
.val())+50);
				$('#loadingbar').css("display","none");
				loading = false;
			});
		}
	}
});
 
$(document).ready(function() {
	$('#loaded_max').val(50);
});
 
// Prevent Multiple Submit of Your Form
$(document).ready(function() {
  $('form').submit(function() {
    if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
      jQuery.data(this, "disabledOnSubmit", { submited: true });
      $('input[type=submit], input[type=button]', this).each(function() {
        $(this).attr("disabled", "disabled");
      });
      return true;
    }
    else
    {
      return false;
    }
  });
});
 
 
/**
 * 微信相关
 * */
var $wx = {
	init: function(){
		var _wx = document.createElement("script");
		_wx.src = "http://res.wx.qq.com/open/js/jweixin-1.0.0.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(_wx, s);
	},
	getDomain: function(){
		var wx_current_domain = cookie.get('wx_current_domain');
		if(wx_current_domain != undefined){
			$wx.share(document.title, document.title, wx_current_domain+'/weixin/authRedirect/shareStore?redirect='+window.location.pathname+window.location.search, window.location.protocol+'//'+window.location.host+'/QWWX/common/img/icon_300.png');
		}else{
			getJson('GET', '/h5/system/getDomain', null, function (data) {
				if(data.result == 'OK'){
					var res = data.body;
					if(res.apiStatus == 0){
						cookie.set('wx_current_domain',res.weixinDomain,1);
						$wx.share(document.title, document.title, res.weixinDomain+'/weixin/authRedirect/shareStore?redirect='+window.location.pathname+window.location.search, window.location.protocol+'//'+window.location.host+'/QWWX/common/img/icon_300.png');
					}else{
						showToast(res.apiMessage,2000);
					}
				}
			});
		}
	},
	share: function(title,desc,link,imgUrl){
		$wx.init();
 
                //var sp = linkUrl.indexOf("?") != -1 ? '&' : '?';
                //var str = sp + 'utm_source=weixin';
                //linkUrl += str; //给所有分享的URL附加来源
 
		var params = { url: window.location.href };
		$.ajax({
			type: 'get',
			url: '/h5/jsApiParams/get',
			dataType : "json",
			data: params,
			success: function(data) {
				if(data.result != 'FAIL'){
					var config = data.body;
					var shareData = { title: title, desc: desc, link: link, imgUrl: imgUrl, type: 'link', dataUrl: '', success: function () { showToast('分享成功!'); }, cancel: function () { } };
					var shareData2 = { title: desc, desc: title, link: link, imgUrl: imgUrl, type: 'link', dataUrl: '', success: function () { showToast('分享成功!'); }, cancel: function () { } };
					var auth_list = ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareQZone','onMenuShareWeibo','hideOptionMenu','showOptionMenu','hideMenuItems','showMenuItems','hideAllNonBaseMenuItem','showAllNonBaseMenuItem'];
					wx.config({debug: false,appId: config.appId,timestamp: config.timestamp,nonceStr: config.nonceStr,signature: config.signature,jsApiList: auth_list });
					wx.ready(function() {
						wx.checkJsApi({ jsApiList:auth_list, error:function(res){ showToast("您的微信客户端太低,请升级后再试!",3000); } });
						wx.onMenuShareTimeline(shareData2);
						wx.onMenuShareAppMessage(shareData);
						wx.onMenuShareQQ(shareData);
						wx.onMenuShareWeibo(shareData);
					});
				}
			}
		});
	}
}
if(navigator.userAgent.indexOf('MicroMessenger') > -1 || navigator.userAgent.indexOf('MQQBrowser') > -1){
	$wx.getDomain();
}
 
//金钱格式化:1234567890 --> 1,234,567,890
var test1 = '1234567890'
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
console.log(format) // 1,234,567,890
 
//当行实现星级
var rate = 1;
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
 
 
// 控制动画
function testAnim(el, animateName, callback) {
    var classname = animateName + ' animated';
    $(el).removeClass(classname).addClass(classname).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
        $(this).removeClass(classname);
        callback && callback();
    });
}
//用法,举个栗子,在click事件中:
var _self = $(this);
testAnim(_self.find('.manito-cates-list'), 'bounceOutUp', function() {
     _self.hide();
});
 
//60秒倒计时 用于发送验证码
//倒计时60秒
var countdown = 60;   
function setTime() {
   if (countdown == 0) {  
      _self.removeClass('disabled');  
      _self.text("获取验证码");  
      countdown = 60;  
      return false;  
   } else {
      _self.addClass('disabled');  
      _self.text(countdown + "s");  
      countdown--;  
   }
   setTimeout(function() {  
       setTime();  
    },1000);  
}
setTime();
版权申明:本文地址 ,本博客所有文章除特别声明外,均采用署名-非商业性使用-禁止演绎 4.0 国际 许可协议。请尊重他人的劳动成果!

我要说两句

  • 2 条回应