搜尋
首頁web前端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
C和JavaScript:連接解釋C和JavaScript:連接解釋Apr 23, 2025 am 12:07 AM

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

從網站到應用程序:JavaScript的不同應用從網站到應用程序:JavaScript的不同應用Apr 22, 2025 am 12:02 AM

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python vs. JavaScript:比較用例和應用程序Python vs. JavaScript:比較用例和應用程序Apr 21, 2025 am 12:01 AM

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C/C在JavaScript口譯員和編譯器中的作用C/C在JavaScript口譯員和編譯器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在行動中:現實世界中的示例和項目JavaScript在行動中:現實世界中的示例和項目Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

了解JavaScript引擎:實施詳細信息了解JavaScript引擎:實施詳細信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python vs. JavaScript:學習曲線和易用性Python vs. JavaScript:學習曲線和易用性Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中