프로그래머가 꼭 알아야 할 35가지 jQuery 코드 조각
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 $('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); }); // 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 = $('html').css('font-size'); $(".resetFont").click(function(){ $('html').css('font-size', originalFontSize); }); // Increase the font size(bigger font0 $(".increaseFont").click(function(){ var currentFontSize = $('html').css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*1.2; $('html').css('font-size', newFontSize); return false; }); // Decrease the font size(smaller font) $(".decreaseFont").click(function(){ var currentFontSize = $('html').css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*0.8; $('html').css('font-size', newFontSize); return false; }); });
9. 페이지 상단 기능으로 복귀
For a smooth(animated) ride back to the top(or any location). $(document).ready(function() { $('a[href*=#]').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); if ($target.length) { var targetOffset = $target.offset().top; $('html,body') .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 $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY); }); // how to use});
11. 위로 가기 버튼
animate 및 scrollTop을 사용하여 맨 위로 돌아가는 애니메이션을 구현할 수 있습니다. 다른 플러그인을 사용하지 않고.// Back to top $('a.top').click(function () { $(document.body).animate({scrollTop: 0}, 800); return false; }); Back to top
12. 이미지 미리 로드
페이지에 보이지 않는 이미지(예: 호버 표시)가 많이 사용되는 경우 해당 이미지를 미리 로드해야 할 수도 있습니다.$.preloadImages = function () { for (var i = 0; i < arguments.length; i++) { $('').attr('src', arguments[i]); } }; $.preloadImages('img/hover1.png', 'img/hover2.png');
13. 이미지가 로드되었는지 확인하세요
다음 작업을 수행하려면 이미지가 로드되었는지 확인해야 하는 경우가 있습니다.$('img').load(function () { console.log('image load successful'); });
14. 깨진 이미지 자동 수정
웹사이트에서 깨진 이미지 링크를 발견하면 쉽게 교체할 수 없는 이미지로 교체할 수 있습니다. . 이 간단한 코드를 추가하면 많은 문제를 줄일 수 있습니다.$('img').on('error', function () { $(this).prop('src', 'img/broken.png'); });
15. 마우스 호버(hover) 전환 클래스 속성
사용자가 클릭 가능한 요소 위에 마우스를 올렸을 때 효과를 변경하려면 다음 코드를 사용하세요. 요소 위로 마우스를 가져갈 때 클래스 속성을 추가하고 사용자가 마우스를 놓으면 자동으로 클래스 속성을 취소할 수 있습니다.$('.btn').hover(function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); }); 你只需要添加必要的CSS代码即可。如果你想要更简洁的代码,可以使用 toggleClass 方法: $('.btn').hover(function () { $(this).toggleClass('hover'); });
16. 입력 필드 비활성화
사용자가 특정 작업을 수행할 때까지 양식의 제출 버튼이나 입력 필드를 비활성화해야 할 수도 있습니다(예: '읽기' 확인). 약관' 확인란). 비활성화된 속성을 활성화하기 전까지는 추가할 수 있습니다.$('input[type="submit"]').prop('disabled', true);
$('input[type="submit"]').removeAttr('disabled');
17. 링크 로드 방지
때때로 페이지에 링크를 걸거나 새로고침하고 싶지 않은 경우 다른 작업을 수행하기를 원할 수도 있습니다. 또는 뭔가 트리거 다른 스크립트의 경우 다음을 수행할 수 있습니다.$('a.no-link').click(function (e) { e.preventDefault(); });
18. 페이드/슬라이드 전환
페이드 및 슬라이드는 우리가 사용하는 것입니다. 애니메이션 효과는 요소가 더 잘 보이도록 하기 위해 jQuery에서 자주 사용됩니다. 하지만 요소가 표시될 때 첫 번째 효과를 사용하고 요소가 사라질 때 두 번째 효과를 사용하려면 다음과 같이 하면 됩니다.// Fade $('.btn').click(function () { $('.element').fadeToggle('slow'); }); // Toggle $('.btn').click(function () { $('.element').slideToggle('slow'); });
19. 간단한 아코디언 효과
아코디언 효과를 얻는 빠르고 쉬운 방법은 다음과 같습니다.// Close all panels $('#accordion').find('.content').hide(); // Accordion $('#accordion').find('.accordion-header').click(function () { var next = $(this).next(); next.slideToggle('fast'); $('.content').not(next).slideUp('fast'); return false; });
20. 두 개의 DIV를 동일한 높이로 만들기
때로는 내부 내용에 관계없이 두 개의 div를 동일한 높이로 만들어야 할 때가 있습니다. 다음 코드 조각을 사용할 수 있습니다.var $columns = $('.column'); 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 ($('#id').html()) { // do something } });
22. 🎜>
$(document).ready(function() { $('#id').replaceWith('I have been replaced'); });
$(document).ready(function() { window.setTimeout(function() { // do something }, 1000); });
25. jquery 개체 컬렉션
$(document).ready(function() { var el = $('#id'); el.html(el.html().replace(/word/ig, "")); });
에 요소가 있는지 확인합니다. 26 . 전체 DIV를 클릭 가능하게 만듭니다
$(document).ready(function() { if ($('#id').length) { // do something } });
27. ID与Class之间转换
当改变Window大小时,在ID与Class之间切换
$(document).ready(function() { function checkWindowSize() { if ( $(window).width() > 1200 ) { $('body').addClass('large'); } else { $('body').removeClass('large'); } } $(window).resize(checkWindowSize); });
28. 克隆对象
$(document).ready(function() { var cloned = $('#id').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[':'], { moreThen1000px: function(a) { return $(a).width() > 1000; } }); $('.box:moreThen1000px').click(function() { // creating a simple js alert box alert('The element that you have clicked is over 1000 pixels wide'); }); });
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('#id').show(); });
以上就是本章的全部内容,更多相关教程请访问jQuery视频教程!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











기사는 JavaScript 라이브러리 작성, 게시 및 유지 관리, 계획, 개발, 테스트, 문서 및 홍보 전략에 중점을 둡니다.

이 기사는 브라우저에서 JavaScript 성능을 최적화하기위한 전략에 대해 설명하고 실행 시간을 줄이고 페이지로드 속도에 미치는 영향을 최소화하는 데 중점을 둡니다.

프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

이 기사는 브라우저 개발자 도구를 사용하여 효과적인 JavaScript 디버깅, 중단 점 설정, 콘솔 사용 및 성능 분석에 중점을 둡니다.

이 기사는 Java의 컬렉션 프레임 워크의 효과적인 사용을 탐구합니다. 데이터 구조, 성능 요구 및 스레드 안전을 기반으로 적절한 컬렉션 (목록, 세트, 맵, 큐)을 선택하는 것을 강조합니다. 효율적인 수집 사용을 최적화합니다

이 기사는 소스 맵을 사용하여 원래 코드에 다시 매핑하여 미니어링 된 JavaScript를 디버그하는 방법을 설명합니다. 소스 맵 활성화, 브레이크 포인트 설정 및 Chrome Devtools 및 Webpack과 같은 도구 사용에 대해 설명합니다.

이 튜토리얼은 Chart.js를 사용하여 파이, 링 및 버블 차트를 만드는 방법을 설명합니다. 이전에는 차트 유형의 차트 유형을 배웠습니다. JS : 라인 차트 및 막대 차트 (자습서 2)와 레이더 차트 및 극지 지역 차트 (자습서 3)를 배웠습니다. 파이 및 링 차트를 만듭니다 파이 차트와 링 차트는 다른 부분으로 나뉘어 진 전체의 비율을 보여주는 데 이상적입니다. 예를 들어, 파이 차트는 사파리에서 남성 사자, 여성 사자 및 젊은 사자의 비율 또는 선거에서 다른 후보자가받는 투표율을 보여주는 데 사용될 수 있습니다. 파이 차트는 단일 매개 변수 또는 데이터 세트를 비교하는 데만 적합합니다. 파이 차트의 팬 각도는 데이터 포인트의 숫자 크기에 의존하기 때문에 원형 차트는 값이 0 인 엔티티를 그릴 수 없습니다. 이것은 비율이 0 인 모든 엔티티를 의미합니다

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.
