16个超实用的jQuery技巧攻略
本文我們將為jQuery用戶分享8個超實用的技巧攻略。jQuery是JavaScript最好的庫之一,主要用于制作動畫、事件處理,支持Ajax及HTML?腳本客戶端。此外,jQuery還擁有各種插件,以幫助開發者在最短時間內快速創建網站/網頁。
?
1)禁用右鍵單擊功能?
如果你想為用戶節省網站信息,那么開發者可以使用這段代碼——禁用右鍵單擊功能。
$(document).ready(function() { //catch the right-click context menu $(document).bind("contextmenu",function(e) { //warning prompt - optional alert("No right-clicking!"); //delete the default context menu return false; }); });?
2)使用jQuery設定文本大小
使用這段代碼,用戶可根據需求重新設定文本尺寸(增加或減少)。
$(document).ready(function() { //find the current font size var originalFontSize = $('html').css('font-size'); //Increase the text size $(".increaseFont").click(function() { var currentFontSize = $('html').css('font-size'); var currentFontSizeNumber = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNumber*1.2; $('html').css('font-size', newFontSize); return false; }); //Decrease the Text Size $(".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; });// Reset Font Size $(".resetFont").click(function(){ $('html').css('font-size', originalFontSize); }); });3)在新窗口打開鏈接?
使用這段代碼會幫助用戶在新窗口打開鏈接,為用戶帶來更好的用戶體驗。?
$(document).ready(function() { //select all anchor tags that have http in the href //and apply the target=_blank $("a[href^='http']").attr('target','_blank'); });?
?
4)更改樣式列表
使用這段代碼幫助你更改樣式列表。?
$(document).ready(function() { $("a.cssSwap").click(function() { //swap the link rel attribute with the value in the rel $('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); }); });?
?
?
5)返回到頂部鏈接
此代碼對于長時間點擊單頁面非常實用,你可以在重要關頭點擊“返回頂部”功能。?
$(document).ready(function() { //when the id="top" link is clicked $('#top').click(function() { //scoll the page back to the top $(document).scrollTo(0,500); } });平滑滾動到錨點
//?HTML: //</pre> <h1?id="anchor">Lorem?Ipsum</h1> <pre> // <a?class="topLink"?href="#anchor">Back?to?Top</a> $(document).ready(function() { $("a.topLink").click(function() { $("html, body").animate({scrollTop: $($(this).attr("href")).offset().top + "px" },{ duration: 500, easing: "swing" }); return false; }); });?
?
6)獲取鼠標指針的X / Y軸
?
$().mousemove(function(e){ //display the x and y axis values inside the P element $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY); });7)檢測當前鼠標坐標?
使用這個腳本,你可以在任何網絡瀏覽器獲取鼠標坐標。?
$(document).ready(function() {$().mousemove(function(e) { $('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY); }); });8)縮放圖片
雖然圖片應該在服務器端縮放,不過如果服務器端未做縮放,需要再客戶端縮放的時候,可以使用下面這個方便的代碼片段:
$(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 });9、滾動時自動加載內容
?
很多網站使用了流行的瀑布圖布局,這種類型的網站在頁面滾動的時候會自動加載內容。下面這段代碼讓你能夠把這個功能搬到你的網站上。
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); });10、檢測密碼強度
?
在表單功能中,經常會有檢測用戶輸入的密碼強度的功能,下面這個代碼片段使用正則表達式來檢測密碼是否足夠安全,當然記得在服務端也進行表單驗證。
$('#pass').keyup(function(e) { var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*[ ubbcodeplace_4 ]quot;, "g"); var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*[ ubbcodeplace_4 ]quot;, "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; });11、均衡元素的高度
?
使用純?CSS代碼實現均衡元素的高度比較困難,而下面這段?jQuery?代碼會根據最高的元素來均衡所有的?Div?元素。
var?maxHeight?=?0; $("div").each(function(){ if ($(this).height() > maxHeight) { maxHeight = $(this).height(); } }); $("div").height(maxHeight);12、修復?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")'); });13、解析?JSON?字符串
?
使用?jQuery?解析?JSON?數據并不復雜。下面是一個高效解析?JSON?數據并將其追加到您的網頁的例子。
function?parseJson(){$.getJSON('hcj.json',getPosts);function getPosts(data){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>';$('body').append(strPost);}} } $(document).ready(function(){ parseJson(); });14、隔行換色
?
這是一個很老的功能了,在大的列表或表格中,隔行顏色可以大大提高內容的可讀性。下面的代碼可以非常簡單實現這個功能。
$('div:odd').css("background-color", "#F4F4F8"); $('div:even').css("background-color", "#EFF1F1");15、預加載圖片
?
你是否注意到?facebook?相冊的圖片加載速度特別快?那是因為在你看到這些圖片之前已經預加載到你的瀏覽器緩存中了。下面是實現這個類似功能的代碼示例:
var?nextimage?=?"/images/some-image.jpg"; $(document).ready(function(){ window.setTimeout(function(){ var img = $("<img>").attr("src", nextimage).load(function(){ }); }, 100); });16、讓整個?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; });?
總結
以上是生活随笔為你收集整理的16个超实用的jQuery技巧攻略的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Uploadify3.2中文提示
- 下一篇: 如何提高新股中签率