作爲輕量級的JS庫,jQuery隨着JavaScrīpt腳本的大熱而備受Web開發者親睞。下面技巧實現的效果雖然並不新鮮,但通過jQuery的封裝,HTML實現了很大的清潔。清爽簡潔又高效的代碼任何時候都是開發者所醉心追求的終極目標,也許它簡單,但是它能量巨大。這裏整理jQuery優化系列的五個jQuery技巧。
一、字體大小的調整。
允許用戶在訪問站點時能自由地調節頁面字體大小,將帶來很好的用戶體驗。下面的代碼就是jQuery要告訴我們怎樣做到這點的:
- //check that the DOM is ready
- $(document).ready(function() {
- //get the current font size
- var originalFontSize = $('html').css('font-size');
- //Increase the font size
- $(".increaseFont").click(function() {
- var currentFontSize = $('html').css('font-size');
- var currentFontSizeNumber = parseFloat(currentFontSize, 10);
- //increases the font- could be set to a value from
- //the user as well
- var newFontSize = currentFontSizeNumber*1.2;
- $('html').css('font-size', newFontSize);
- return false;
- });
- //Decrease the Font Size
- $(".decreaseFont").click(function() {
- var currentFontSize = $('html').css('font-size');
- var currentFontSizeNum = parseFloat(currentFontSize, 10);
- //decreases font. Could be set to a value from
- //the user as well
- var newFontSize = currentFontSizeNum*0.8;
- $('html').css('font-size', newFontSize);
- return false;
- });
- // Reset Font Size
- $(".resetFont").click(function(){
- $('html').css('font-size', originalFontSize);
- });
- });
建立增減字體大小的樣式。
二、在新窗口打開鏈接
爲了讓訪問者儘量停留在自己的站點上,我們通常會設置在新窗口打開所有外部鏈接。但在XHTML 1.0中,是沒有“_blank”標籤屬性的。在這類情況下,使用以下jQuery技巧就可以避免這個問題,並能在新窗口中打開所有外部鏈接。
- //check that the DOM is ready
- $(document).ready(function() {
- //select all anchor tags that have http in the href
- //and apply the target=_blank
- $("a[href^='http']").attr('target','_blank');
- });
這樣就行了!現在,所有的外部鏈接都可以從一個新窗口打開,以便用戶留在原頁面。如果原頁面使用了很多外部文檔的鏈接,如PDF或DOC文件,那我們可以創建一些規則以便在新窗口中加載這些文件。
三、交換樣式表
除了允許訪問者改變頁面字體大小,還可以允許訪問者通過選擇不同的頁面主題樣式來感受不同的頁面風格。
- //check that the DOM is ready
- $(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'));
- });
- });
四、禁用右鍵
通常禁用右鍵是爲了防止訪問者直接從頁面拷貝信息,或者是想創建自己獨特的右鍵功能。當然,不管什麼原因,禁用右鍵可以通過以下代碼實現:
- //check that the DOM is ready
- $(document).ready(function() {
- //catch the right-click context menu
- $(document).bind("contextmenu",function(e) {
- //warning prompt - optional
- alert("No right-clicking!");
- //cancel the default context menu
- return false;
- });
- });
jQuery使我們更容易使用右鍵來對網頁進行處理。
五、返回頂部鏈接
如果頁面過長,可能通過增加“返回頂部”的鏈接來使訪問者方便地返回頁面頂部。這是一個簡單的JavaScript效果,我們可以通過jQuery運用滾動效果增添一點點小技巧。
- $(document).ready(function() {
- //when the id="top" link is clicked
- $('#top').click(function() {
- //scoll the page back to the top
- $(document).scrollTo(0,500);
- }
- });
對於擁有長頁面的站點來說,這真是一個必備功能。
當成爲一個jQuery熟手時,一定會發現更多的諸如此類的開發技巧。加油!