經驗分享:10個簡單實用的jQuery程式碼片段
儘管各種 JavaScirpt 框架和庫層出不窮,jQuery 仍然是 Web 前端開發中最常用的工具庫。今天,向大家分享我覺得在網站開發中10個簡單實用的 jQuery 程式碼片段。
平滑滾動到錨點
這個功能很常見,在網站底部新增一個讓訪客快速回到頁面頂部的功能,下面是實現這個功能的示例程式碼:
// HTML: // <h1 id="anchor">Lorem Ipsum</h1> // <p><a href="#anchor" class="topLink">Back to Top</a></p> $(document).ready(function() { $("a.topLink").click(function() { $("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top + "px" }, { duration: 500, easing: "swing" }); return false; }); });
縮放圖片
雖然圖片應該在伺服器端縮放,不過如果伺服器端未做縮放,需要再客戶端縮放的時候,可以使用下面這個方便的程式碼片段:
$(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 });
滾動時自動載入內容
很多網站使用了流行的瀑布圖佈局,這種型別的網站在頁面滾動的時候會自動載入內容。下面這段程式碼讓你能夠把這個功能搬到你的網站上。
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?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); });
檢測密碼強度
在表單功能中,經常會有檢測使用者輸入的密碼強度的功能,下面這個程式碼片段使用正規表示式來檢測密碼是否足夠安全,當然記得在服務端也進行表單驗證。
$(`#pass`).keyup(function(e) { var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*W).*$", "g"); var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g"); var enoughRegex = new RegExp("(?=.{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; });
均衡元素的高度
使用純 CSS程式碼實現均衡元素的高度比較困難,而下面這段 jQuery 程式碼會根據最高的元素來均衡所有的 Div 元素。
var maxHeight = 0; $("div").each(function(){ if ($(this).height() > maxHeight) { maxHeight = $(this).height(); } }); $("div").height(maxHeight);
修復 IE6 PNG 問題
至今,IE6 在國內仍然佔據了大量的份額,因此在 Web 開發中仍然需要考慮 IE6 的相容問題。比較常用的 IE6 PNG 圖片問題,下面這段程式碼可以方便的修復。
$(`.pngfix`).each( function() { $(this).attr(`writing-mode`, `tb-rl`); $(this).css(`background-image`, `none`); $(this).css( `filter`, `progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="scale")`); });
解析 JSON 字串
使用 jQuery 解析 JSON 資料並不複雜。下面是一個高效解析 JSON 資料並將其追加到您的網頁的例子。
function parseJson(){ //Start by calling the json object, I will be using a //file from my own site for the tutorial //Then we declare a callback function to process the data $.getJSON(`hcj.json`,getPosts); //The process function, I am going to get the title, //url and excerpt for 5 latest posts function getPosts(data){ //Start a for loop with a limit of 5 for(var i = 0; i < 5; i++){ var strPost = `<h2>` + data.posts[i].title + `</h2>` + `<p>` + data.posts[i].excerpt + `</p>` + `<a href="` + data.posts[i].url + `" title="Read ` + data.posts[i].title + `">Read ></a>`; //Append the body with the string $(`body`).append(strPost); } } } //Fire off the function in your document ready $(document).ready(function(){ parseJson(); });
隔行換色
這是一個很老的功能了,在大的列表或表格中,隔行顏色可以大大提高內容的可讀性。下面的程式碼可以非常簡單實現這個功能。
$(`div:odd`).css("background-color", "#F4F4F8"); $(`div:even`).css("background-color", "#EFF1F1");
預載入圖片
你是否注意到 facebook 相簿的圖片載入速度特別快?那是因為在你看到這些圖片之前已經預載入到你的瀏覽器快取中了。下面是實現這個類似功能的程式碼示例:
var nextimage = "/images/some-image.jpg"; $(document).ready(function(){ window.setTimeout(function(){ var img = $("<img>").attr("src", nextimage).load(function(){ //all done }); }, 100); });
讓整個 Div 可點選
這是實現連結的父 Div 也能夠點選的簡單方法,HTML 示例程式碼如下:
<div class="myBox"> blah blah blah. <a href="http://google.com">link</a> </div>
下面的 jQuery 程式碼讓整個 Div 可點選:
$(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false; });
英文連結:Catswhocode: Useful jQuery code snippets
編譯來源:夢想天空 ◆ 關注前端開發技術 ◆ 分享網頁設計資源
作者:山邊小溪
主站:yyyweb.com 記住啦:)
歡迎任何形式的轉載,但請務必註明出處。
相關文章
- 幾個超級實用的css程式碼片段CSS
- Jquery實現的高亮效果程式碼分享jQuery
- jquery 實現滑動條的簡單驗證jQuery
- 實現一個簡單的 jQuery 的 APIjQueryAPI
- 分享8個非常時髦的翻頁特效(附程式碼片段)特效
- 分享前端開發常用程式碼片段前端
- 30秒內便能學會的30個超實用Python程式碼片段Python
- 用Java程式碼實現一個簡單的聊天室功能Java
- 【程式碼鑑賞】簡單優雅的JavaScript程式碼片段(二):流控和重試JavaScript
- Flutter上你需要一個簡單實用的驗證碼輸入WidgetFlutter
- Golang, 以 9 個簡短程式碼片段,弄懂 defer 的使用特點Golang
- 18個常用的JavaScript片段分享JavaScript
- 10個程式設計好習慣:優秀程式設計師的經驗分享程式設計師
- Pet:一個簡單的命令列片段管理器命令列
- 程式碼片段
- 一個簡單的區塊鏈程式碼實現區塊鏈
- jQuery Validate表單驗證(使用者註冊簡單應用)jQuery
- 使用 implode.io 記錄分享你的程式碼片段
- 三個Rust程式碼庫的經驗分享:何時開始使用Rust? - convexRust
- 實驗三:在centos裡使用一些簡單的程式碼,CentOS
- 網站製作中常見的10個 HTML5 程式碼片段整理網站HTML
- CSS jquery圓角帶陰影的導航選單程式碼分享CSSjQuery
- RN程式碼片段
- Netflix採用GraphQL的經驗分享
- GitHub CSP應用的經驗分享Github
- 進行了1000多次程式碼評審的經驗分享 - DEVdev
- 實現簡單的`Blazor`低程式碼Blazor
- Python實現簡單驗證碼的轉文字Python
- 分享兩個實用的shell指令碼指令碼
- BBIN波音館開心消消樂簡單又易懂的攻略技巧打法分享個人多年的經驗
- MATLAB神經網路工具箱(程式碼簡單實現)Matlab神經網路
- C# 程式開發中經常遇到的10條實用的程式碼C#
- 分享一些簡單的 Laravel 編碼實踐Laravel
- jQuery簡單實用的響應式固定側邊欄外掛jQuery
- Gorm常用程式碼片段GoORM
- 實用的管理經驗
- 一個前端碼農的 Flutter 實戰經驗前端Flutter
- 分享一個簡單的 laravel 應用健康檢查命令Laravel
- 使用TensorFlow 來實現一個簡單的驗證碼識別過程