【转】jQuery代码片段备用
在CSDN看到的,记下备用。原文:http://www.csdn.net/article/2013-07-16/2816238-15-jquery-code-snippets-for-developers
jQuery里提供了许多创建交互式网站的方法,在开发Web项目时,开发人员应该好好利用jQuery代码,它们不仅能给网站带来各种动画、特效,还会提高网站的用户体验。
本文收集了15段非常实用的jQuery代码片段,你可以直接复制黏贴到代码里,但请开发者注意了,要理解代码再使用哦。下面就让我们一起来享受jQuery代码的魅力之处吧。
1.预加载图片
(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.preLoadImages("image1.gif", "/path/to/image2.png");
2. 让页面中的每个元素都适合在移动设备上展示
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' }); };
3.图像等比例缩放
$(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 });
4.返回页面顶部
1 // Back To Top 2 $(document).ready(function(){ 3 $('.top').click(function() { 4 $(document).scrollTo(0,500); 5 }); 6 }); 7 //Create a link defined with the class .top 8 <a href="#" class="top">Back To Top</a>
5.使用jQuery打造手风琴式的折叠效果
1 var accordion = { 2 init: function(){ 3 var $container = $('#accordion'); 4 $container.find('li:not(:first) .details').hide(); 5 $container.find('li:first').addClass('active'); 6 $container.on('click','li a',function(e){ 7 e.preventDefault(); 8 var $this = $(this).parents('li'); 9 if($this.hasClass('active')){ 10 if($('.details').is(':visible')) { 11 $this.find('.details').slideUp(); 12 } else { 13 $this.find('.details').slideDown(); 14 } 15 } else { 16 $container.find('li.active .details').slideUp(); 17 $container.find('li').removeClass('active'); 18 $this.addClass('active'); 19 $this.find('.details').slideDown(); 20 } 21 }); 22 } 23 };
6.通过预加载图片廊中的上一幅下一幅图片来模仿Facebook的图片展示方式
1 var nextimage = "/images/some-image.jpg"; 2 $(document).ready(function(){ 3 window.setTimeout(function(){ 4 var img = $("").attr("src", nextimage).load(function(){ 5 //all done 6 }); 7 }, 100); 8 });
7.使用jQuery和Ajax自动填充选择框
1 $(function(){ 2 $("select#ctlJob").change(function(){ 3 $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){ 4 var options = ''; 5 for (var i = 0; i < j.length; i++) { 6 options += ' 7 ' + j[i].optionDisplay + ' 8 '; 9 } 10 $("select#ctlPerson").html(options); 11 }) 12 }) 13 })
8.自动替换丢失的图片
1 // Safe Snippet 2 $("img").error(function () { 3 $(this).unbind("error").attr("src", "missing_image.gif"); 4 }); 5 // Persistent Snipper 6 $("img").error(function () { 7 $(this).attr("src", "missing_image.gif"); 8 });
9.在鼠标悬停时显示淡入/淡出特效
1 $(document).ready(function(){ 2 $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads 3 $(".thumbs img").hover(function(){ 4 $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover 5 },function(){ 6 $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout 7 }); 8 });
10.清空表单数据
1 function clearForm(form) { 2 // iterate over all of the inputs for the form 3 // element that was passed in 4 $(':input', form).each(function() { 5 var type = this.type; 6 var tag = this.tagName.toLowerCase(); // normalize case 7 // it's ok to reset the value attr of text inputs, 8 // password inputs, and textareas 9 if (type == 'text' || type == 'password' || tag == 'textarea') 10 this.value = ""; 11 // checkboxes and radios need to have their checked state cleared 12 // but should *not* have their 'value' changed 13 else if (type == 'checkbox' || type == 'radio') 14 this.checked = false; 15 // select elements need to have their 'selectedIndex' property set to -1 16 // (this works for both single and multiple select elements) 17 else if (tag == 'select') 18 this.selectedIndex = -1; 19 }); 20 };
11.预防对表单进行多次提交
1 $(document).ready(function() { 2 $('form').submit(function() { 3 if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') { 4 jQuery.data(this, "disabledOnSubmit", { submited: true }); 5 $('input[type=submit], input[type=button]', this).each(function() { 6 $(this).attr("disabled", "disabled"); 7 }); 8 return true; 9 } 10 else 11 { 12 return false; 13 } 14 }); 15 });
12.动态添加表单元素
//change event on password1 field to prompt new input $('#password1').change(function() { //dynamically create new input and insert after password1 $("#password1").append(""); });
13.让整个Div可点击
blah blah blah. link The following lines of jQuery will make the entire div clickable: $(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false; });
14.平衡高度或Div元素
1 var maxHeight = 0; 2 $("div").each(function(){ 3 if ($(this).height() > maxHeight) { maxHeight = $(this).height(); } 4 }); 5 $("div").height(maxHeight);
15. 在窗口滚动时自动加载内容
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); });