jQuery里提供了许多创建交互式网站的方法,在开发Web项目时,开发人员应该好好利用jQuery代码,它们不仅能给网站带来各种动画、特效,还会提高网站的用户体验。
本文收集了15段非常实用的jQuery代码片段,你可以直接复制黏贴到代码里,但请开发者注意了,要理解代码再使用哦。下面就让我们一起来享受jQuery代码的魅力之处吧。
1.预加载图片
Js代码
1. (function($) {
2. var
3.
4. // Arguments are image paths relative to the current page.
5. function() {
6. var
7. for (var
8. var cacheImage = document.createElement('img');
9. cacheImage.src = arguments[i];
10. cache.push(cacheImage);
11. }
12. }
13. jQuery.preLoadImages("image1.gif", "/path/to/image2.png");
2. 让页面中的每个元素都适合在移动设备上展示
Js代码
1. var scr = document.createElement('script');
2. scr.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js');
3. document.body.appendChild(scr);
4. scr.onload = function(){
5. 'div').attr('class', '').attr('id', '').css({
6. 'margin'
7. 'padding'
8. 'width': '100%',
9. 'clear':'both'
10. });
11. };
3.图像等比例缩放
Js代码
1. $(window).bind("load", function() {
2.
3. // IMAGE RESIZE
4. '#product_cat_list img').each(function() {
5. var
6. var
7. var
8. var width = $(this).width();
9. var height = $(this).height();
10. if(width > maxWidth){
11. ratio = maxWidth / width;
12. this).css("width", maxWidth);
13. this).css("height", height * ratio);
14. height = height * ratio;
15. }
16. var width = $(this).width();
17. var height = $(this).height();
18. if(height > maxHeight){
19. ratio = maxHeight / height;
20. this).css("height", maxHeight);
21. this).css("width", width * ratio);
22. width = width * ratio;
23. }
24. });
25.
26. //$("#contentpage img").show();
27.
28. // IMAGE RESIZE
29. });
4.返回页面顶部
Js代码
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打造手风琴式的折叠效果
Js代码
1. var
2. function(){
3. var $container = $('#accordion');
4. 'li:not(:first) .details').hide();
5. 'li:first').addClass('active');
6. '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. 'li.active .details').slideUp();
17. 'li').removeClass('active');
18. this.addClass('active');
19. this.find('.details').slideDown();
20. }
21. });
22. }
23. };
6.通过预加载图片廊中的上一幅下一幅图片来模仿Facebook的图片展示方式
Js代码
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自动填充选择框
Js代码
1. $(function(){
2. $("select#ctlJob").change(function(){
3. $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
4. var options = '';
5. for (var
6. options += '
7. ' + j[i].optionDisplay + '
8. ';
9. }
10. $("select#ctlPerson").html(options);
11. })
12. })
13. })
8.自动替换丢失的图片
Js代码
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.在鼠标悬停时显示淡入/淡出特效
Js代码
1. $(document).ready(function(){
2. ".thumbs img").fadeTo("slow", 0.6);
3. // This sets the opacity of the thumbs to fade down to 60% when the page loads
4. ".thumbs img").hover(function(){
5. this).fadeTo("slow", 1.0);
6. // This should set the opacity to 100% on hover
7. function(){
8. this).fadeTo("slow", 0.6);
9. // This should set the opacity back to 60% on mouseout
10. });
11. });
10.清空表单数据
Js代码
1. function
2.
3. // iterate over all of the inputs for the form
4.
5. // element that was passed in
6. ':input', form).each(function() {
7. var type = this.type;
8. var tag = this.tagName.toLowerCase();
9. // normalize case
10.
11. // it's ok to reset the value attr of text inputs,
12.
13. // password inputs, and textareas
14. if (type == 'text' || type == 'password' || tag == 'textarea')
15. this.value = "";
16. // checkboxes and radios need to have their checked state cleared
17. // but should *not* have their 'value' changed
18. else if (type == 'checkbox' || type == 'radio')
19. this.checked = false;
20. // select elements need to have their 'selectedIndex' property set to -1
21. // (this works for both single and multiple select elements)
22. else if (tag == 'select')
23. this.selectedIndex = -1;
24. });
25. };
11.预防对表单进行多次提交
Js代码
1. $(document).ready(function() {
2. 'form').submit(function() {
3. if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
4. 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.动态添加表单元素
Js代码
1. //change event on password1 field to prompt new input
2. $('#password1').change(function() {
3.
4. //dynamically create new input and insert after password1
5. "#password1").append("");
6. });
13.让整个Div可点击
Js代码
1. blah blah blah. link
2. 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元素
Js代码
1. var
2. $("div").each(function(){
3. if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
4. });
5. $("div").height(maxHeight);
15. 在窗口滚动时自动加载内容
Js代码
1. var loading = false;
2. $(window).scroll(function(){
3. if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
4. if(loading == false){
5. true;
6. '#loadingbar').css("display","block");
7. "load.php?start="+$('#loaded_max').val(), function(loaded){
8. 'body').append(loaded);
9. '#loaded_max').val(parseInt($('#loaded_max').val())+50);
10. '#loadingbar').css("display","none");
11. false;
12. });
13. }
14. }
15. });
16. $(document).ready(function() {
17. '#loaded_max').val(50);
18. });