찾다
웹 프론트엔드JS 튜토리얼18가지 멋진 jQuery 코드 조각_jquery

1、jQuery实现的内链接平滑滚动
不需要使用太复杂的插件,只要使用下载这段代码即可实现基于内部链接的平滑滚动

$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
 
var anchor = this.hash,
$target = $(target);
 
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 500, 'swing', function () {
window.location.hash = anchor;
});
 
});

2、使用jQuery获取所有节点

var $element = $('#gbtags');
 var $nodes = $element.contents();
 $nodes.each(function() {
  if(this.nodeType === 3 && $.trim($(this).text())) {
  $(this).wrap('');
 }
});

3、限制选择框选择个数

$("#categories option").click(function(e){
 if ($(this).parent().val().length < 2) {
  $(this).removeAttr("selected");
 }
});

4、jQuery使用通配符来删除class

var _c = 'your-icon-class'
 
$('.currency').removeClass (function (index, css) {
 return (css.match (/\bicon-\S+/g) || []).join(' ');
}).addClass('icon-'+_c);

5、切换启用和禁用

/* HTML
|
|
<input type="text" value="欢迎访问www.admin10000.com" /><input type="button" value="禁用按钮" />
|
|
*/
 
// Plugin
(function ($) {
 $.fn.toggleDisabled = function () {
  return this.each(function () {
   var $this = $(this);
   if ($this.attr('disabled')) $this.removeAttr('disabled');
   else $this.attr('disabled', 'disabled');
  });
 };
})(jQuery);
 
// TEST
$(function () {
 $('input:button').click(function () {
  $('input:text').toggleDisabled();
 });
});

6、平滑滚动返回顶端

<h1 id="admin-com">admin10000.com</h1>
<a class="topLink" href="#anchor">返回顶端</a>
 
$(document).ready(function () {
 
 $("a.topLink").click(function () {
  $("html, body").animate({
   scrollTop: $($(this).attr("href")).offset().top + "px"
  }, {
   duration: 500,
   easing: "swing"
  });
  return false;
 });
 
});

7、使用jQuery和Google Analytics来跟踪表单

var array1 = [];
$(document).ready(function () {
 $('input').change(function () {
  var formbox = $(this).attr('id');
  array1.push(formbox);
  console.log("you filled out box " + array1);
 });
 $('#submit').click(function () {
  console.log('tracked ' + array1);
  //alert('this is the order of boxes you filled out: ' + array1);
  _gaq.push(['_trackEvent', 'Form', 'completed', '"' + array1 + '"']);
 });
});

8、超简单的密码强度提示

$('#pass').keyup(function (e) {
 var strongRegex = new RegExp("^(&#63;=.{8,})(&#63;=.*[A-Z])(&#63;=.*[a-z])(&#63;=.*[0-9])(&#63;=.*\W).*$", "g");
 var mediumRegex = new RegExp("^(&#63;=.{7,})(((&#63;=.*[A-Z])(&#63;=.*[a-z]))|((&#63;=.*[A-Z])(&#63;=.*[0-9]))|((&#63;=.*[a-z])(&#63;=.*[0-9]))).*$", "g");
 var enoughRegex = new RegExp("(&#63;=.{6,}).*", "g");
 if (false == enoughRegex.test($(this).val())) {
  $('#passstrength').html('More Characters');
 } else if (strongRegex.test($(this).val())) {
  $('#passstrength').className = 'ok';
  $('#passstrength').html('Strong!');
 } else if (mediumRegex.test($(this).val())) {
  $('#passstrength').className = 'alert';
  $('#passstrength').html('Medium!');
 } else {
  $('#passstrength').className = 'error';
  $('#passstrength').html('Weak!');
 }
 return true;
});

9、jQuery生成一个自动停靠页尾效果

// Window load event used just in case window height is dependant upon images
$(window).bind("load", function () {
 var footerHeight = 0,
  footerTop = 0,
  $footer = $("#footer");
 positionFooter();
 
 function positionFooter() {
  footerHeight = $footer.height();
  footerTop = ($(window).scrollTop() + $(window).height() - footerHeight) + "px";
  /* DEBUGGING
console.log("Document height: ", $(document.body).height());
console.log("Window height: ", $(window).height());
console.log("Window scroll: ", $(window).scrollTop());
console.log("Footer height: ", footerHeight);
console.log("Footer top: ", footerTop);
*/
  if (($(document.body).height() + footerHeight) < $(window).height()) {
   $footer.css({
    position: "absolute"
   }).stop().animate({
    top: footerTop
   });
  } else {
   $footer.css({
    position: "static"
   });
  }
 }
 
 $(window)
  .scroll(positionFooter)
  .resize(positionFooter);
});

10、预防对表单进行多次提交

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

11、图像等比例缩放

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

12、鼠标滑动时的渐入和渐出

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

13、制作等高的列

var max_height = 0;
$("div.col").each(function(){
 if ($(this).height() > max_height) { max_height = $(this).height(); }
});
$("div.col").height(max_height);

14、图片预加载

(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");

15、获取 URL 中传递的参数

$.urlParam = function(name){
 var results = new RegExp('[\\&#63;&]' + name + '=([^&#]*)').exec(window.location.href);
 if (!results) { return 0; }
 return results[1] || 0;
}

16、禁用表单的回车键提交

$("#form").keypress(function(e) {
 if (e.which == 13) {
 return false;
 }
});

17、让整个DIV可以被点击

<div class = "myBox" > 
 < a href = "http://www.jb51.net" > www.jb51.net < /a>
</div > 
 
$(".myBox").click(function(){
 window.location=$(this).find("a").attr("href");
 return false;
});

18、在新窗口打开链接 (target=”blank”)   

$('a[@rel$='external']').click(function(){
   this.target = "_blank";
});

 大家可以结合之前小编整理的文章进行学习,把实用的jQuery代码片段进行汇总,以便日后学习使用。

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

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

JavaScript 엔진 이해 : 구현 세부 사항JavaScript 엔진 이해 : 구현 세부 사항Apr 17, 2025 am 12:05 AM

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python vs. JavaScript : 학습 곡선 및 사용 편의성Python vs. JavaScript : 학습 곡선 및 사용 편의성Apr 16, 2025 am 12:12 AM

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

Python vs. JavaScript : 커뮤니티, 라이브러리 및 리소스Python vs. JavaScript : 커뮤니티, 라이브러리 및 리소스Apr 15, 2025 am 12:16 AM

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

C/C에서 JavaScript까지 : 모든 것이 어떻게 작동하는지C/C에서 JavaScript까지 : 모든 것이 어떻게 작동하는지Apr 14, 2025 am 12:05 AM

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

JavaScript 엔진 : 구현 비교JavaScript 엔진 : 구현 비교Apr 13, 2025 am 12:05 AM

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

브라우저 너머 : 실제 세계의 JavaScript브라우저 너머 : 실제 세계의 JavaScriptApr 12, 2025 am 12:06 AM

실제 세계에서 JavaScript의 응용 프로그램에는 서버 측 프로그래밍, 모바일 애플리케이션 개발 및 사물 인터넷 제어가 포함됩니다. 1. 서버 측 프로그래밍은 Node.js를 통해 실현되며 동시 요청 처리에 적합합니다. 2. 모바일 애플리케이션 개발은 재교육을 통해 수행되며 크로스 플랫폼 배포를 지원합니다. 3. Johnny-Five 라이브러리를 통한 IoT 장치 제어에 사용되며 하드웨어 상호 작용에 적합합니다.

Next.js (백엔드 통합)로 멀티 테넌트 SAAS 애플리케이션 구축Next.js (백엔드 통합)로 멀티 테넌트 SAAS 애플리케이션 구축Apr 11, 2025 am 08:23 AM

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

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

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.