>  기사  >  웹 프론트엔드  >  직접 사용할 수 있는 15가지 jQuery 코드 조각_jquery

직접 사용할 수 있는 15가지 jQuery 코드 조각_jquery

WBOY
WBOY원래의
2016-05-16 15:38:171168검색

당신이 출판한 기사 "수집해야 할 매우 유용한 10가지 PHP 코드 조각"? 이 기사에서 저자는 계속해서 매우 유용한 15가지 jQuery 코드 조각을 제공할 것입니다.

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. 페이지 상단으로 돌아가기

// Back To Top 
$(document).ready(function(){  
 $('.top').click(function() {  
   $(document).scrollTo(0,500);  
 }); 
});  
//Create a link defined with the class .top 
<a href="#" class="top">Back To Top</a> 

5. jQuery를 사용하여 아코디언 스타일의 접기 효과 만들기

var accordion = { 
   init: function(){ 
      var $container = $('#accordion'); 
      $container.find('li:not(:first) .details').hide(); 
      $container.find('li:first').addClass('active'); 
      $container.on('click','li a',function(e){ 
         e.preventDefault(); 
         var $this = $(this).parents('li'); 
         if($this.hasClass('active')){ 
             if($('.details').is(':visible')) { 
                $this.find('.details').slideUp(); 
             } else { 
                $this.find('.details').slideDown(); 
             } 
         } else { 
             $container.find('li.active .details').slideUp(); 
             $container.find('li').removeClass('active'); 
             $this.addClass('active'); 
             $this.find('.details').slideDown(); 
         } 
      }); 
   } 
}; 

6. 이미지 갤러리에 이전 이미지와 다음 이미지를 미리 로딩하여 페이스북의 이미지 표시 방식을 모방

var nextimage = "/images/some-image.jpg"; 
$(document).ready(function(){ 
window.setTimeout(function(){ 
var img = $("").attr("src", nextimage).load(function(){ 
//all done 
}); 
}, 100); 
}); 

7. jQuery와 Ajax를 사용하여 선택 상자 자동 채우기

$(function(){ 
$("select#ctlJob").change(function(){ 
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){ 
var options = ''; 
for (var i = 0; i < j.length; i++) { 
options += ' 
' + j[i].optionDisplay + ' 
'; 
} 
$("select#ctlPerson").html(options); 
}) 
}) 
}) 

8. 손실된 사진 자동 교체

// Safe Snippet 
$("img").error(function () { 
  $(this).unbind("error").attr("src", "missing_image.gif"); 
}); 
// Persistent Snipper 
$("img").error(function () { 
  $(this).attr("src", "missing_image.gif"); 
}); 

9. 마우스 오버 시 페이드인/페이드아웃 효과 표시

$(document).ready(function(){ 
  $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads 
  $(".thumbs img").hover(function(){ 
    $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover 
  },function(){ 
    $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout 
  }); 
}); 

10. 양식 데이터 지우기

function clearForm(form) { 
 // iterate over all of the inputs for the form 
 // element that was passed in 
 $(':input', form).each(function() { 
  var type = this.type; 
  var tag = this.tagName.toLowerCase(); // normalize case 
  // it's ok to reset the value attr of text inputs, 
  // password inputs, and textareas 
  if (type == 'text' || type == 'password' || tag == 'textarea') 
   this.value = ""; 
  // checkboxes and radios need to have their checked state cleared 
  // but should *not* have their 'value' changed 
  else if (type == 'checkbox' || type == 'radio') 
   this.checked = false; 
  // select elements need to have their 'selectedIndex' property set to -1 
  // (this works for both single and multiple select elements) 
  else if (tag == 'select') 
   this.selectedIndex = -1; 
 }); 
}; 

11. 양식 다중 제출 방지

$(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; 
  } 
 }); 
}); 

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 요소

var maxHeight = 0; 
$("div").each(function(){ 
  if ($(this).height() > maxHeight) { maxHeight = $(this).height(); } 
}); 
$("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&#63;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); 
}); 

이 기사에 수집된 매우 실용적인 15개의 jQuery 코드 조각을 복사하여 코드에 직접 붙여넣을 수 있지만 개발자는 사용하기 전에 코드를 이해하는 것이 좋습니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.