프로그래머가 꼭 알아야 할 35가지 jQuery 코드 조각

PHPz
풀어 주다: 2018-09-29 09:16:33
원래의
1146명이 탐색했습니다.

jQuery는 이제 웹 개발에서 가장 인기 있는 JavaScript 라이브러리가 되었습니다. jQuery와 수많은 플러그인을 통해 다양하고 멋진 효과를 쉽게 얻을 수 있습니다. 이 기사에서는 jQuery를 보다 효율적으로 사용하는 데 도움이 되는 몇 가지 실용적인 jQuery 기술을 소개합니다.

빠른 개발에 도움이 되는 jQuery 팁/코드 조각 35개를 모았습니다.

1. 마우스 오른쪽 버튼 클릭 비활성화

$(document).ready(function(){
  $(document).bind("contextmenu",function(e){
    return false;
  });
});
로그인 후 복사

2. 검색 텍스트 상자 텍스트 숨기기

Hide when clicked in the search field, the value.(example can be found below in the comment fields)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
  textFill($('input.text1'));
});
  function textFill(input){ //input focus text function
   var originalvalue = input.val();
   input.focus( function(){
     if( $.trim(input.val()) == originalvalue ){ input.val(''); }
   });
   input.blur( function(){
     if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
   });
}
로그인 후 복사

3. 새 창에서 링크 열기

XHTML 1.0 Strict doesn't allow this attribute in the code, so use this to keep the code valid.
$(document).ready(function() {
  //Example 1: Every link will open in a new window
  $('a[href^="http://"]').attr("target", "_blank");
  //Example 2: Links with the rel="external" attribute will only open in a new window
  $('a[@rel$='external']').click(function(){
   this.target = "_blank";
  });
});
// how to useopen link
로그인 후 복사

4. 브라우저 감지

참고: jQuery 1.4 버전에서는 $.support가 $.browser 변수를 대체했습니다

$(document).ready(function() {
// Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ){
  // do something
}
// Target Safari
if( $.browser.safari ){
  // do something
}
// Target Chrome
if( $.browser.chrome){
  // do something
}
// Target Camino
if( $.browser.camino){
  // do something
}
// Target Opera
if( $.browser.opera){
  // do something
}
// Target IE6 and below
if ($.browser.msie && $.browser.version  6){
  // do something
}
});
로그인 후 복사

5. 이미지 미리 로드

This piece of code will prevent the loading of all images, which can be useful if you have a site with lots of images.
$(document).ready(function() {
jQuery.preloadImages = function()
{
 for(var i = 0; i<ARGUMENTS.LENGTH; jQuery(?").attr("src", arguments[i]);
 }
}
// how to use
$.preloadImages("image1.jpg");
});
로그인 후 복사

6. 페이지 스타일 전환

$(document).ready(function() {
  $("a.Styleswitcher").click(function() {
    //swicth the LINK REL attribute with the value in A REL attribute
    $(&#39;link[rel=stylesheet]&#39;).attr(&#39;href&#39; , $(this).attr(&#39;rel&#39;));
  });
// how to use
// place this in your header// the linksDefault ThemeRed ThemeBlue Theme});
로그인 후 복사

7. 열 높이가 동일합니다

두 개의 CSS 열을 사용하는 경우 이 방법을 사용하여 두 열의 높이를 동일하게 만들 수 있습니다. 같은 .

$(document).ready(function() {
function equalHeight(group) {
  tallest = 0;
  group.each(function() {
    thisHeight = $(this).height();
    if(thisHeight > tallest) {
      tallest = thisHeight;
    }
  });
  group.height(tallest);
}
// how to use
$(document).ready(function() {
  equalHeight($(".left"));
  equalHeight($(".right"));
});
});
로그인 후 복사

8. 페이지 글꼴 크기를 동적으로 제어

사용자가 페이지 글꼴 크기를 변경할 수 있습니다

$(document).ready(function() {
 // Reset the font size(back to default)
 var originalFontSize = $(&#39;html&#39;).css(&#39;font-size&#39;);
  $(".resetFont").click(function(){
  $(&#39;html&#39;).css(&#39;font-size&#39;, originalFontSize);
 });
 // Increase the font size(bigger font0
 $(".increaseFont").click(function(){
  var currentFontSize = $(&#39;html&#39;).css(&#39;font-size&#39;);
  var currentFontSizeNum = parseFloat(currentFontSize, 10);
  var newFontSize = currentFontSizeNum*1.2;
  $(&#39;html&#39;).css(&#39;font-size&#39;, newFontSize);
  return false;
 });
 // Decrease the font size(smaller font)
 $(".decreaseFont").click(function(){
  var currentFontSize = $(&#39;html&#39;).css(&#39;font-size&#39;);
  var currentFontSizeNum = parseFloat(currentFontSize, 10);
  var newFontSize = currentFontSizeNum*0.8;
  $(&#39;html&#39;).css(&#39;font-size&#39;, newFontSize);
  return false;
 });
});
로그인 후 복사

9. 페이지 상단 기능으로 복귀

For a smooth(animated) ride back to the top(or any location).
$(document).ready(function() {
$(&#39;a[href*=#]&#39;).click(function() {
 if (location.pathname.replace(/^\//,&#39;&#39;) == this.pathname.replace(/^\//,&#39;&#39;)
 && location.hostname == this.hostname) {
  var $target = $(this.hash);
  $target = $target.length && $target
  || $(&#39;[name=&#39; + this.hash.slice(1) +&#39;]&#39;);
  if ($target.length) {
 var targetOffset = $target.offset().top;
 $(&#39;html,body&#39;)
 .animate({scrollTop: targetOffset}, 900);
  return false;
  }
 }
 });
// how to use
// place this where you want to scroll to// the linkgo to top});
로그인 후 복사

10. 🎜>

Want to know where your mouse cursor is?
$(document).ready(function() {
  $().mousemove(function(e){
   //display the x and y axis values inside the div with the id XY
  $(&#39;#XY&#39;).html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
 });
// how to use});
로그인 후 복사

11. 위로 가기 버튼

animate 및 scrollTop을 사용하여 맨 위로 돌아가는 애니메이션을 구현할 수 있습니다. 다른 플러그인을 사용하지 않고.

// Back to top
$(&#39;a.top&#39;).click(function () {
 $(document.body).animate({scrollTop: 0}, 800);
 return false;
});
Back to top
로그인 후 복사
scrollTop의 값을 변경하면 return과 top 사이의 거리를 조정할 수 있으며, animate의 두 번째 매개변수는 return 작업을 수행하는 데 필요한 시간입니다(단위: 밀리초). ).

12. 이미지 미리 로드

페이지에 보이지 않는 이미지(예: 호버 표시)가 많이 사용되는 경우 해당 이미지를 미리 로드해야 할 수도 있습니다.

$.preloadImages = function () {
 for (var i = 0; i < arguments.length; i++) {
  $(&#39;&#39;).attr(&#39;src&#39;, arguments[i]);
 }
};
$.preloadImages(&#39;img/hover1.png&#39;, &#39;img/hover2.png&#39;);
로그인 후 복사

13. 이미지가 로드되었는지 확인하세요

다음 작업을 수행하려면 이미지가 로드되었는지 확인해야 하는 경우가 있습니다.

$(&#39;img&#39;).load(function () {
 console.log(&#39;image load successful&#39;);
});
로그인 후 복사
img를 다른 ID나 클래스로 대체하면 지정된 이미지가 로드되는지 확인할 수 있습니다.

14. 깨진 이미지 자동 수정

웹사이트에서 깨진 이미지 링크를 발견하면 쉽게 교체할 수 없는 이미지로 교체할 수 있습니다. . 이 간단한 코드를 추가하면 많은 문제를 줄일 수 있습니다.

$(&#39;img&#39;).on(&#39;error&#39;, function () {
 $(this).prop(&#39;src&#39;, &#39;img/broken.png&#39;);
});
로그인 후 복사
사이트에 깨진 이미지 링크가 없더라도 이 코드를 추가해도 아무런 해가 없습니다.

15. 마우스 호버(hover) 전환 클래스 속성

사용자가 클릭 가능한 요소 위에 마우스를 올렸을 때 효과를 변경하려면 다음 코드를 사용하세요. 요소 위로 마우스를 가져갈 때 클래스 속성을 추가하고 사용자가 마우스를 놓으면 자동으로 클래스 속성을 취소할 수 있습니다.


$(&#39;.btn&#39;).hover(function () {
 $(this).addClass(&#39;hover&#39;);
 }, function () {
  $(this).removeClass(&#39;hover&#39;);
 });
你只需要添加必要的CSS代码即可。如果你想要更简洁的代码,可以使用 toggleClass 方法:
$(&#39;.btn&#39;).hover(function () { 
 $(this).toggleClass(&#39;hover&#39;); 
});
로그인 후 복사
참고: CSS를 직접 사용하여 달성 이 효과는 더 나은 해결책일 수 있지만 여전히 방법을 알아야 합니다.

16. 입력 필드 비활성화

사용자가 특정 작업을 수행할 때까지 양식의 제출 버튼이나 입력 필드를 비활성화해야 할 수도 있습니다(예: '읽기' 확인). 약관' 확인란). 비활성화된 속성을 활성화하기 전까지는 추가할 수 있습니다.


$(&#39;input[type="submit"]&#39;).prop(&#39;disabled&#39;, true);
로그인 후 복사
removeAttr 메소드를 실행하고 제거할 속성을 매개변수로 전달하기만 하면 됩니다.


$(&#39;input[type="submit"]&#39;).removeAttr(&#39;disabled&#39;);
로그인 후 복사

17. 링크 로드 방지

때때로 페이지에 링크를 걸거나 새로고침하고 싶지 않은 경우 다른 작업을 수행하기를 원할 수도 있습니다. 또는 뭔가 트리거 다른 스크립트의 경우 다음을 수행할 수 있습니다.


$(&#39;a.no-link&#39;).click(function (e) {
 e.preventDefault();
});
로그인 후 복사

18. 페이드/슬라이드 전환

페이드 및 슬라이드는 우리가 사용하는 것입니다. 애니메이션 효과는 요소가 더 잘 보이도록 하기 위해 jQuery에서 자주 사용됩니다. 하지만 요소가 표시될 때 첫 번째 효과를 사용하고 요소가 사라질 때 두 번째 효과를 사용하려면 다음과 같이 하면 됩니다.


// Fade
$(&#39;.btn&#39;).click(function () {
 $(&#39;.element&#39;).fadeToggle(&#39;slow&#39;);
});
// Toggle
$(&#39;.btn&#39;).click(function () {
 $(&#39;.element&#39;).slideToggle(&#39;slow&#39;);
});
로그인 후 복사

19. 간단한 아코디언 효과

아코디언 효과를 얻는 빠르고 쉬운 방법은 다음과 같습니다.


// Close all panels
$(&#39;#accordion&#39;).find(&#39;.content&#39;).hide();
// Accordion
$(&#39;#accordion&#39;).find(&#39;.accordion-header&#39;).click(function () {
 var next = $(this).next();
 next.slideToggle(&#39;fast&#39;);
 $(&#39;.content&#39;).not(next).slideUp(&#39;fast&#39;);
 return false;
});
로그인 후 복사

20. 두 개의 DIV를 동일한 높이로 만들기

때로는 내부 내용에 관계없이 두 개의 div를 동일한 높이로 만들어야 할 때가 있습니다. 다음 코드 조각을 사용할 수 있습니다.

var $columns = $(&#39;.column&#39;);
var height = 0;
$columns.each(function () {
 if ($(this).height() > height) {
  height = $(this).height();
 }
});
$columns.height(height);
로그인 후 복사
이 코드는 요소 그룹을 반복하고 높이를 요소 중 최대 높이로 설정합니다.

21. 요소가 비어 있는지 확인

This will allow you to check if an element is empty.
$(document).ready(function() {
 if ($(&#39;#id&#39;).html()) {
  // do something
  }
});
로그인 후 복사

22. 🎜>

23. jQuery 지연 로딩 기능
$(document).ready(function() {
  $(&#39;#id&#39;).replaceWith(&#39;I have been replaced&#39;);
});
로그인 후 복사

24. 🎜>
$(document).ready(function() {
  window.setTimeout(function() {
   // do something
  }, 1000);
});
로그인 후 복사

25. jquery 개체 컬렉션

$(document).ready(function() {
  var el = $(&#39;#id&#39;);
  el.html(el.html().replace(/word/ig, ""));
});
로그인 후 복사

에 요소가 있는지 확인합니다. 26 . 전체 DIV를 클릭 가능하게 만듭니다

$(document).ready(function() {
  if ($(&#39;#id&#39;).length) {
 // do something
 }
});
로그인 후 복사

27. ID与Class之间转换

当改变Window大小时,在ID与Class之间切换

$(document).ready(function() {
  function checkWindowSize() {
  if ( $(window).width() > 1200 ) {
    $(&#39;body&#39;).addClass(&#39;large&#39;);
  }
  else {
    $(&#39;body&#39;).removeClass(&#39;large&#39;);
  }
  }
$(window).resize(checkWindowSize);
});
로그인 후 복사

28. 克隆对象

$(document).ready(function() {
  var cloned = $(&#39;#id&#39;).clone();
// how to use});
로그인 후 복사

29. 使元素居屏幕中间位置

$(document).ready(function() {
 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");
   return this;
 }
 $("#id").center();
});
로그인 후 복사

30. 写自己的选择器

$(document).ready(function() {
  $.extend($.expr[&#39;:&#39;], {
    moreThen1000px: function(a) {
      return $(a).width() > 1000;
   }
  });
 $(&#39;.box:moreThen1000px&#39;).click(function() {
   // creating a simple js alert box
   alert(&#39;The element that you have clicked is over 1000 pixels wide&#39;);
 });
});
로그인 후 복사

31. 统计元素个数

$(document).ready(function() {
  $("p").size();
});
로그인 후 복사

32. 使用自己的 Bullets

$(document).ready(function() {
  $("ul").addClass("Replaced");
  $("ul > li").prepend("‒ ");
 // how to use
 ul.Replaced { list-style : none; }
});
로그인 후 복사

33. 引用Google主机上的Jquery类库

//Example 1
로그인 후 복사

34. 禁用Jquery(动画)效果

$(document).ready(function() {
  jQuery.fx.off = true;
});
로그인 후 복사

35. 与其他Javascript类库冲突解决方案

$(document).ready(function() {
  var $jq = jQuery.noConflict();
  $jq(&#39;#id&#39;).show();
});
로그인 후 복사

以上就是本章的全部内容,更多相关教程请访问jQuery视频教程

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!