本页二维码,扫一扫分享到朋友圈
朋友圈

jQuery常用实用代码


阅读174 评论0 赞 44返回首页    go 编程与技术  go javascript


前言

在开发过程中,有很多代码片段是可以进行复用的,以后在此对jQuery的有用代码段进行整理,方便日后的使用。


DOM操作相关

嵌套的过滤器

1

2

3

4

5

//允许你减少集合中的匹配元素的过滤器,

//只剩下那些与给定的选择器匹配的部分。在这种情况下,

//查询删除了任何没(:not)有(:has)

//包含class为“selected”(.selected)的子节点。

.filter(":not(:has(.selected))")

找到节点索引号

1

2

3

$("ul > li").click(function(){

varindex = $(this).prevAll().length;

});

检测是否存在

1

2

3

if($('#someDiv').length) {

//万岁!!!它存在……

}


动效相关

滑动到页面顶部

1

2

3

$("a[href='#top']").click(function(){

$("html, body").animate({scrollTop:0},"slow");

returnfalse;});

滚动到某位置

1

2

3

4

5

6

7

8

jQuery.fn.autoscroll =function(selector){

$('html,body').animate(

{scrollTop: $(selector).offset().top},

500

};

}

//然后像这样来滚动到你希望去到的class/area上。

$('.area_name').autoscroll();

固定到顶部

允许一个元素固定到顶部

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

$(function(){

var$win = $(window)

var$nav = $('.mytoolbar');

varnavTop = $('.mytoolbar').length && $('.mytoolbar').offset().top;

varisFixed=0;

processScroll()

$win.on('scroll', processScroll)

functionprocessScroll(){

vari, scrollTop = $win.scrollTop()

if(scrollTop >= navTop && !isFixed) {

isFixed =1

$nav.addClass('subnav-fixed')

}elseif(scrollTop <= navTop && isFixed) {

isFixed =0

$nav.removeClass('subnav-fixed')

}}

下滑超过移动位置固定下滑隐藏

先来一个简单版的,超过了头图区域就fixed,回到了头图就取消fixed:

1

2

3

4

5

6

7

8

9

10

11

12

;(function(jq, g){

varscrollmenu = $('#scrollmenu');

$(window).on('scroll',function(){

var_scrollTop = $(window).scrollTop();

if(_scrollTop >=300){

scrollmenu.addClass('f-pf');

}else{

scrollmenu.removeClass('f-pf');

}

});

})(jQuery,window);

这里综合了上滑和下滑的判断,还有超过指定区域高度就固定的算法。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

var_currentScrollTop =0;

$(window).on('scroll',function(){

var_scrollTop = $(window).scrollTop();

if(_scrollTop >= _currentScrollTop){

_currentScrollTop = _scrollTop;

//向下滑动

if(!_isFixed && (_scrollTop >= _navTop)){

_isFixed =true;

mainDOM._mainNavFix.addClass('f-pf');

}

}else{

_isFixed =false;

mainDOM._mainNavFix.removeClass('f-pf');

_currentScrollTop = _scrollTop;

}

});

侧边栏区域定位组件

组件代码:

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

(function(jq,g){

functionInitSlider(){

returnthis.init.apply(this,arguments);

}

vartemplate ='<div class="m-sliBox f-pa">\

<div class="m-sliBox-head f-pr" style="background-position-y:45px;">\

<div class="goto f-pa f-dn">返回主会场</div>\

</div>\

<div class="m-sliBox-body">\

<ul class="j-lists lists">\

</ul>\

</div>\

<div class="m-sliBox-foot"></div>\

</div>';

var_pro = InitSlider.prototype;

_pro.init =function(data){

if(!data){

return;

}

var_this =this;

this.data = data;

this.offsetTop = [];

this.tpl=$(template);

this.lists =this.tpl.find('.j-lists');

this.setLists();

this.show();

setTimeout(function(){

_this.bindEvent();

},500);

};

/*根据传入的内容拼接结构*/

_pro.setLists =function(){

var_len =this.data.length;

var_str ='';

for(vari=0;i<_len;i++){

_str = _str +'<li data-sour="'+this.data[i].class+'">'+this.data[i].name +'</li>';

}

this.lists.append($(_str));

};

_pro.bindEvent =function(){

var_len =this.data.length;

var_this =this;

/*获取各模块高度存于数组*/

for(vari=0;i<_len;i++){

this.offsetTop[i] = $('.'+this.data[i].class).offset().top;

}

this.lists.on('click','li',function(){

/*防止闪烁触发*/

$(window).off('scroll',handleScroll);

setTimeout(function(){

$(window).on('scroll',handleScroll);

},500);

var_sour = $(this).data('sour');

$('html,body').animate({

scrollTop:$('.'+_sour).offset().top+20

},500);

$(this).addClass('z-act').siblings().removeClass('z-act');

});

$(window).on('scroll',handleScroll);

/*滑动时实时于高度数组进行比较,判断处于哪一区域*/

functionhandleScroll(){

var_nowOffsetTop = $(window).scrollTop();

var_children = _this.lists.children();

for(vari=0;i<_len;i++){

if(_nowOffsetTop>_this.offsetTop[i]&&_nowOffsetTop<_this.offsetTop[i+1]){

_children.eq(i).addClass('z-act').siblings().removeClass('z-act');

}

if(_nowOffsetTop>_this.offsetTop[_len-1]){

_children.eq(_len-1).addClass('z-act').siblings().removeClass('z-act');

}

}

};

};

_pro.show =function(){

$('#j-special-sliderNew').prepend(this.tpl);

};

jq.showSlider =function(data){

returnnewInitSlider(data);

};

})(jQuery,window);

使用时在指定div命名class,并传参即可:

1

2

3

4

5

6

7

8

9

10

11

12

(function(jq, g){

jq(document).ready(function(jq){

$.showSlider([

{'class':'j-live','name':'直播预告'},

{'class':'j-micro','name':'热门微专业'},

{'class':'j-design','name':'设计&产品类'},

{'class':'j-it','name':'技术类'},

{'class':'j-data','name':'数据类'},

{'class':'j-other','name':'其他类'}

]);

});

})(jQuery,window);

效果展示:

demo

倒计时

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

(function(jq,g){

vartimer =null;

varend;

vartoZero;

varbtn =document.getElementById("btn");

varoDay = $('.j-day');

varoHour = $('.j-hour');

varoMinute = $('.j-min');

varoSecond = $('.j-sec');

toZero = oDay.innerHTML = oHour.innerHTML = oMinute.innerHTML = oSecond.innerHTML ="00";

end =1472960973980;

countDown();

timer = setInterval(countDown,1000);

functioncountDown(){  

vartimedate =newDate(end);//结束时间

varnow = $.getCurServerTime();

//var now = new Date(1472559291702); //获取当前时间

//var now = new Date(); //获取当前时间

//var date = (timedate.getTime() - now.getTime()) / 1000; //获取相差的秒数

vardate =Math.floor(end-now)/1000;

varday =Math.floor(date / (60*60*24));

var_hour = date - day *60*60*24;

varhour =Math.floor(_hour / (60*60));

var_minute = _hour - hour *60*60;

varminute =Math.floor(_minute / (60));

var_second = _minute - minute *60;

varsecond =Math.floor(_second);

functiontoDou(n){

if(n <10) {

return'0'+ n;

}else{

return''+ n;

}

}//一位数的数字前面加0

if(date >0) {

oDay.html(toDou(day));

oHour.html(toDou(hour));

oMinute.html(toDou(minute));

oSecond.html(toDou(second));

}else{

clearInterval(timer);

toZero;

}

}

})(jQuery,window);

效果如下:

;

出现在屏幕中心

1

2

3

4

5

6

7

8

jQuery.fn.center =function(){

this.css('position','absolute');

this.css('top', ( $(window).height() -this.height() ) /2+$(window).scrollTop() +'px');

this.css('left', ( $(window).width() -this.width() ) /2+$(window).scrollLeft() +'px');

returnthis;

}

//这样来使用上面的函数:

$(element).center();

鼠标位置

1

2

3

4

5

$(document).ready(function() {

$(document).mousemove(function(e){

$(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);

});

});

一屏一屏滚动

自己做了一个插件,原理就是利用translateY进行变换来显示不同的屏幕。

目前只是监听了鼠标滚轮事件,后期可以拓展键盘事件和移动端事件。

demo

插件代码:

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

;(function($,window){

varMyFullPage =function(element,options){

this.$element = element;

this.defaults = {

'parent':'scrollContainer',

'className':'slide',

'interval':1000,

'startDomIndex':1

};

this.options = $.extend({},this.defaults,options);

this.domLength =0;

};

varpro = MyFullPage.prototype;

pro.initFullPage =function(){

this.setDomInfo();

this.setDomStyle();

this.setPageAction();

this.bindMouseWheel(this.pageAction);

}

/*获取需要的节点信息*/

pro.setDomInfo =function(){

this.parentNode =this.$element.find('.'+this.options.parent);

this.slideNodes =this.$element.find('.'+this.options.className);

this.domLength =this.slideNodes.length;

this.currentDom =this.options.startDomIndex;

}

/*构造相关样式*/

pro.setDomStyle =function(){

var_interval =this.options.interval/1000;

this.$element.css({

'position':'fixed',

'top':0,

'right':0,

'bottom':0,

'left':0,

'z-index':9999,

'overflow':'hidden'

});

this.parentNode.css({

'display':'none',

'transition':'all ease '+_interval+'s'

});

this.height =this.$element.height();

this.slideNodes.css('height',this.height+'px');

this.parentNode.show();

}

/*构造动作器*/

pro.setPageAction =function(){

var_this =this;

this.pageAction = {

isScrolling:false,

next:function(){

if((_this.currentDom +1)<= _this.domLength){

_this.currentDom +=1;

_this.pageAction.move(_this.currentDom);

}

},

pre:function(){

if(_this.currentDom-1>0){

_this.currentDom -=1;

_this.pageAction.move(_this.currentDom);

}

},

move:function(index){

_this.pageAction['isScrolling'] =true;

vardi = -(index-1)*(_this.height) +'px';

_this.pageAction['start'] = +newDate();

_this.parentNode.css('transform','translateY('+di+')');

setTimeout(function(){

_this.pageAction['isScrolling'] =false;

},_this.options.interval-0+10);

}

}

};

/*添加鼠标滚动事件*/

pro.bindMouseWheel =function(page){

vartype ='mousewheel';

vardeltaY =0;

functionmouseWheelHandle(event){

if(page.isScrolling) {// 加锁部分

returnfalse;

}

vare = event.originalEvent || event;

deltaY = e.deltaY;

if(deltaY >0) {

page.next();

}elseif(deltaY <0) {

page.pre();

}

}

$(document).on('mousewheel', mouseWheelHandle);

}

/*挂载jquery插件*/

$.fn.myFullPage =function(options){

varmyFullPage =newMyFullPage(this,options);

myFullPage.initFullPage();

}

})(jQuery,window)


性能优化与工程处理相关

预加载图片

1

2

3

4

5

6

7

jQuery.preloadImages =function(){

for(vari =0; i <arguments.length; i++) {

$("<img />").attr('src',arguments[i]);

}

};

//用法

$.preloadImages('image1.gif','/path/to/image2.png','some/image3.jpg');

自动定位并修复图片

1

2

$('img').error(function(){

$(this).attr('src','img/broken.png');});

禁用右键单击上下文菜单

1

2

3

$(document).bind('contextmenu',function(e){

returnfalse;

});

鼠标右键和左键

1

2

3

4

5

6

7

$("#someelement").on('click',function(e){

if( (!$.browser.msie && e.button ==0) || ($.browser.msie && e.button ==1) ) {

alert("Left Mouse Button Clicked");

}elseif(e.button ==2) {

alert("Right Mouse Button Clicked");

}

});

限制textarea字符个数

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

jQuery.fn.maxLength = function(max){

this.each(function(){

var type = this.tagName.toLowerCase();

var inputType = this.type? this.type.toLowerCase() : null;

if(type == "input" && inputType == "text" || inputType == "password"){

//Apply the standard maxLength

this.maxLength = max;

}

else if(type == "textarea"){

this.onkeypress = function(e){

var ob = e || event;

var keyCode = ob.keyCode;

var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;

return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);

};

this.onkeyup = function(){

if(this.value.length > max){

this.value = this.value.substring(0,max);

}

};

}

});

};

//用法

$('#mytextarea').maxLength(500);

文本输入禁止使用空格

1

2

3

4

$('input.nospace').keydown(function(e){

if(e.keyCode ==32) {

returnfalse;

}});


工具函数相关

遍历map格式

有时候后端传回来的值不一定是个数组,也有可能是map格式,如下:

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

vardata = {

"key_0": [

{

"productId":1002996021,

"productName":"和秋叶一起学PPT",

"productType":0,

"productCnt":null,

},

{

"productId":940019,

"productName":"课程的名称很长会怎么样呢课程的名称很长会怎么样呢",

"productType":0,

"productCnt":null,

},

{

"productId":940019,

"productName":"课程1",

"productType":0,

"productCnt":3,

}

],

"key_1": [

{

"productId":1002996021,

"productName":"和秋叶一起学PPT",

"productType":0,

"productCnt":null,

},

{

"productId":940019,

"productName":"课程的名称很长会怎么样呢课程的名称很长会怎么样呢",

"productType":0,

"productCnt":null,

},

{

"productId":940019,

"productName":"课程1",

"productType":0,

"productCnt":3,

}

]

}

这个时候需要用到$.map方法来对应解析:

1

2

3

4

$.map(data,function(val,key){

console.log(key);

console.log(JSON.stringify(val));

});

demo


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

;(function($, window, document,undefined){

//定义Beautifier的构造函数

varBeautifier =function(ele, opt){

this.$element = ele,

this.defaults = {

'color':'red',

'fontSize':'12px',

'textDecoration':'none'

},

this.options = $.extend({},this.defaults, opt)

}

//定义Beautifier的方法

Beautifier.prototype = {

beautify:function(){

returnthis.$element.css({

'color':this.options.color,

'fontSize':this.options.fontSize,

'textDecoration':this.options.textDecoration

});

}

}

//在插件中使用Beautifier对象

$.fn.myPlugin =function(options){

//创建Beautifier的实体

//this指向挂载的节点

varbeautifier =newBeautifier(this, options);

//调用其方法

returnbeautifier.beautify();

}

})(jQuery,window,document);


  上一篇:go 浏览器javascript跨域问题解决办法
  下一篇:go jQuery的deferred对象详解


评论


用QQ登录管理/创建网站 用微博登录管理/创建网站   发布于:11-19