Web前端的35個jQuery小技巧

来源:http://www.cnblogs.com/zengzhaoguang/archive/2016/05/24/5524036.html
-Advertisement-
Play Games

1. 禁止右鍵點擊 $(document).ready(function(){ $(document).bind("contextmenu",function(e){ return false; }); }); 2. 隱藏搜索文本框文字 Hide when clicked in the search ...


1. 禁止右鍵點擊
$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});

2. 隱藏搜索文本框文字
Hide when clicked in the search field, the value.(example can be found below in the comment fields)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
   textFill($('input.text1'));
});
    function textFill(input){ //input focus text function
     var originalvalue = input.val();
     input.focus( function(){
          if( $.trim(input.val()) == originalvalue ){ input.val(''); }
     });
     input.blur( function(){
          if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
     });
}

3. 在新視窗中打開鏈接
XHTML 1.0 Strict doesn’t allow this attribute in the code, so use this to keep the code valid.
$(document).ready(function() {
   //Example 1: Every link will open in a new window
   $('a[href^="http://"]').attr("target", "_blank");
   //Example 2: Links with the rel="external" attribute will only open in a new window
   $('a[@rel$='external']').click(function(){
      this.target = "_blank";
   });
});
// how to use
<a href="http://www.opensourcehunter.com" rel=external>open link</a>

4. 檢測瀏覽器
註: 在版本jQuery 1.4中,$.support 替換掉了$.browser 變數
$(document).ready(function() {
// Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ){
    // do something
}
// Target Safari
if( $.browser.safari ){
    // do something
}
// Target Chrome
if( $.browser.chrome){
    // do something
}
// Target Camino
if( $.browser.camino){
    // do something
}
// Target Opera
if( $.browser.opera){
    // do something
}
// Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ){
    // do something
}
// Target anything above IE6
if ($.browser.msie && $.browser.version > 6){
    // do something
}
});

5. 預載入圖片
This piece of code will prevent the loading of all images, which can be useful if you have a site with lots of images.
$(document).ready(function() {
jQuery.preloadImages = function()
{
  for(var i = 0; i<ARGUMENTS.LENGTH; jQuery(?<img { i++)>").attr("src", arguments[i]);
  }
}
// how to use
$.preloadImages("image1.jpg");
});

6. 頁面樣式切換
$(document).ready(function() {
    $("a.Styleswitcher").click(function() {
        //swicth the LINK REL attribute with the value in A REL attribute
        $('link[rel=stylesheet]').attr('href' , $(this).attr('rel'));
    });
// how to use
// place this in your header
<LINK rel=stylesheet type=text/css href="default.css">
// the links
<A href="#" rel=default.css>Default Theme</A>
<A href="#" rel=red.css>Red Theme</A>
<A href="#" rel=blue.css>Blue Theme</A>
});

7. 列高度相同
如果使用了兩個CSS列,使用此種方式可以是兩列的高度相同。
$(document).ready(function() {
function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}
// how to use
$(document).ready(function() {
    equalHeight($(".left"));
    equalHeight($(".right"));
});
});

8. 動態控制頁面字體大小,用戶可以改變頁面字體大小
$(document).ready(function() {
  // Reset the font size(back to default)
  var originalFontSize = $('html').css('font-size');
    $(".resetFont").click(function(){
    $('html').css('font-size', originalFontSize);
  });
  // Increase the font size(bigger font0
  $(".increaseFont").click(function(){
    var currentFontSize = $('html').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*1.2;
    $('html').css('font-size', newFontSize);
    return false;
  });
  // Decrease the font size(smaller font)
  $(".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;
  });
});

9. 返回頁面頂部功能
For a smooth(animated) ride back to the top(or any location).
$(document).ready(function() {
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'')
&& location.hostname == this.hostname) {
   var $target = $(this.hash);
   $target = $target.length && $target
   || $('[name=' + this.hash.slice(1) +']');
   if ($target.length) {
  var targetOffset = $target.offset().top;
  $('html,body')
  .animate({scrollTop: targetOffset}, 900);
    return false;
   }
  }
  });
// how to use
// place this where you want to scroll to
<A name=top></A>
// the link
<A href="#top">go to top</A>
});

10. 獲得滑鼠指針XY值
Want to know where your mouse cursor is?
$(document).ready(function() {
   $().mousemove(function(e){
     //display the x and y axis values inside the div with the id XY
    $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
  });
// how to use
<DIV id=XY></DIV>
});

11.返回頂部按鈕
你可以利用 animate 和 scrollTop 來實現返回頂部的動畫,而不需要使用其他插件。
// Back to top
$('a.top').click(function () {
  $(document.body).animate({scrollTop: 0}, 800);
  return false;
});
<!-- Create an anchor tag -->
<a href="#">Back to top</a>
改變 scrollTop 的值可以調整返回距離頂部的距離,而 animate 的第二個參數是執行返回動作需要的時間(單位:毫秒)。

12.預載入圖片
如果你的頁面中使用了很多不可見的圖片(如:hover 顯示),你可能需要預載入它們:
$.preloadImages = function () {
  for (var i = 0; i < arguments.length; i++) {
    $('<img>').attr('src', arguments[i]);
  }
};
$.preloadImages('img/hover1.png', 'img/hover2.png');

13.檢查圖片是否載入完成
有時候你需要確保圖片完成載入完成以便執行後面的操作:
$('img').load(function () {
  console.log('image load successful');
});
你可以把 img 替換為其他的 ID 或者 class 來檢查指定圖片是否載入完成。

14.自動修改破損圖像
如果你碰巧在你的網站上發現了破碎的圖像鏈接,你可以用一個不易被替換的圖像來代替它們。添加這個簡單的代碼可以節省很多麻煩:
$('img').on('error', function () {
  $(this).prop('src', 'img/broken.png');
});
即使你的網站沒有破碎的圖像鏈接,添加這段代碼也沒有任何害處。

15.滑鼠懸停(hover)切換 class 屬性
假如當用戶滑鼠懸停在一個可點擊的元素上時,你希望改變其效果,下麵這段代碼可以在其懸停在元素上時添加 class 屬性,當用戶滑鼠離開時,則自動取消該 class 屬性:
$('.btn').hover(function () {
  $(this).addClass('hover');
  }, function () {
    $(this).removeClass('hover');
  });
你只需要添加必要的CSS代碼即可。如果你想要更簡潔的代碼,可以使用 toggleClass 方法:
$('.btn').hover(function () {
  $(this).toggleClass('hover');
});
註:直接使用CSS實現該效果可能是更好的解決方案,但你仍然有必要知道該方法。

16.禁用 input 欄位
有時你可能需要禁用表單的 submit 按鈕或者某個 input 欄位,直到用戶執行了某些操作(例如,檢查“已閱讀條款”覆選框)。可以添加 disabled 屬性,直到你想啟用它時:
$('input[type="submit"]').prop('disabled', true);
你要做的就是執行 removeAttr 方法,並把要移除的屬性作為參數傳入:
$('input[type="submit"]').removeAttr('disabled');

17.阻止鏈接載入
有時你不希望鏈接到某個頁面或者重新載入它,你可能希望它來做一些其他事情或者觸發一些其他腳本,你可以這麼做:
$('a.no-link').click(function (e) {
  e.preventDefault();
});

18.切換 fade/slide
fade 和 slide 是我們在 jQuery 中經常使用的動畫效果,它們可以使元素顯示效果更好。但是如果你希望元素顯示時使用第一種效果,而消失時使用第二種效果,則可以這麼做:
// Fade
$('.btn').click(function () {
  $('.element').fadeToggle('slow');
});
// Toggle
$('.btn').click(function () {
  $('.element').slideToggle('slow');
});

19.簡單的手風琴效果
這是一個實現手風琴效果快速簡單的方法:
// Close all panels
$('#accordion').find('.content').hide();
// Accordion
$('#accordion').find('.accordion-header').click(function () {
  var next = $(this).next();
  next.slideToggle('fast');
  $('.content').not(next).slideUp('fast');
  return false;
});

20.讓兩個 DIV 高度相同
有時你需要讓兩個 div 高度相同,而不管它們裡面的內容多少。可以使用下麵的代碼片段:
var $columns = $('.column');
var height = 0;
$columns.each(function () {
  if ($(this).height() > height) {
    height = $(this).height();
  }
});
$columns.height(height);
這段代碼會迴圈一組元素,並設置它們的高度為元素中的最大高。

21. 驗證元素是否為空
This will allow you to check if an element is empty.
$(document).ready(function() {
  if ($('#id').html()) {
   // do something
   }
});

22. 替換元素
$(document).ready(function() {
   $('#id').replaceWith('
<DIV>I have been replaced</DIV>
');
});

23. jQuery延時載入功能
$(document).ready(function() {
   window.setTimeout(function() {
     // do something
   }, 1000);
});

24. 移除單詞功能
$(document).ready(function() {
   var el = $('#id');
   el.html(el.html().replace(/word/ig, ""));
});

25. 驗證元素是否存在於jquery對象集合中
$(document).ready(function() {
   if ($('#id').length) {
  // do something
  }
});

26. 使整個DIV可點擊
$(document).ready(function() {
    $("div").click(function(){
      //get the url from href attribute and launch the url
      window.location=$(this).find("a").attr("href"); return false;
    });
// how to use
<DIV><A href="index.html">home</A></DIV>

});

27. ID與Class之間轉換
當改變Window大小時,在ID與Class之間切換
$(document).ready(function() {
   function checkWindowSize() {
    if ( $(window).width() > 1200 ) {
        $('body').addClass('large');
    }
    else {
        $('body').removeClass('large');
    }
   }
$(window).resize(checkWindowSize);
});

28. 克隆對象
$(document).ready(function() {
   var cloned = $('#id').clone();
// how to use
<DIV id=id></DIV>

});

29. 使元素居屏幕中間位置
$(document).ready(function() {
  jQuery.fn.center = function () {
      this.css("position","absolute");
      this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
      this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
      return this;
  }
  $("#id").center();
});

30. 寫自己的選擇器
$(document).ready(function() {
   $.extend($.expr[':'], {
       moreThen1000px: function(a) {
           return $(a).width() > 1000;
      }
   });
  $('.box:moreThen1000px').click(function() {
      // creating a simple js alert box
      alert('The element that you have clicked is over 1000 pixels wide');
  });
});

31. 統計元素個數
$(document).ready(function() {
   $("p").size();
});

32. 使用自己的 Bullets
$(document).ready(function() {
   $("ul").addClass("Replaced");
   $("ul > li").prepend("‒ ");
// how to use
ul.Replaced { list-style : none; }
});

33. 引用Google主機上的Jquery類庫(谷歌用不了,可以用百度CDN)
//Example 1
<SCRIPT src="http://www.google.com/jsapi"></SCRIPT>
<SCRIPT type=text/javascript>
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
    // do something
});
</SCRIPT><SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>
// Example 2:(the best and fastest way)
<SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>

34. 禁用Jquery(動畫)效果
$(document).ready(function() {
    jQuery.fx.off = true;
});

35. 與其他Javascript類庫衝突解決方案
$(document).ready(function() {
   var $jq = jQuery.noConflict();
   $jq('#id').show();
});


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • align-content 作用: 會設置自由盒內部各個項目在垂直方向排列方式。 條件:必須對父元素設置自由盒屬性display:flex;,並且設置排列方式為橫向排列flex-direction:row;並且設置換行,flex-wrap:wrap;這樣這個屬性的設置才會起作用。 設置對象: 這個屬 ...
  • Vue.js報錯Failed to resolve filter問題原因 金剛 vue Vue.js js javascript 之前使用vue.js寫分頁功能時,寫了一個過濾器,發現一個比較奇怪的錯誤。 console控制台調試的時候 提示錯誤消息: Failed to resolve filte ...
  • 1.前言 上一篇jQuery分析(2)中瞭解了jQuery庫的骨架實現原理,這就好比搖滾音樂,搖滾音樂不是某種音樂他就像一個音樂盒子,裡面包含了各種不同的搖滾風格(山地、朋克、鄉村、流行、硬搖、金屬、迷幻等)。那麼上一篇只是大致瞭解了jQuery的基本形狀,從這篇文章開始會深入jQuery庫的各種函 ...
  • 前言 React 的核心思想是:封裝組件,各個組件維護自己的狀態和 UI,當狀態變更,自動重新渲染整個組件。 最近前端界鬧的沸沸揚揚的技術當屬 了,加上項目需要等等原因,自己也決定花些時間來好好認識下這個東西。然後花時間自己寫了一個demo: , 你可以先 "點這裡去看react todo" rea ...
  • 動畫屬性 背景屬性 邊框(Border) 和 輪廓(Outline) 屬性 盒子(Box) 屬性 顏色(Color) 屬性 內邊距(Padding) 屬性 媒體頁面內容屬性 尺寸(Dimension) 屬性 彈性盒子模型(Flexible Box) 屬性 字體(Font) 屬性 內容生成屬性(Gen ...
  • 效果:http://hovertree.com/texiao/css3/24/效果圖:代碼如下: 轉自:http://hovertree.com/h/bjaf/css3xingxi.htm 特效彙總:http://www.cnblogs.com/roucheng/p/texiao.html ...
  • 二刷《高程》第八章BOM筆記整理。 如果要在Web中使用JavaScript,那麼BOM(瀏覽器對象模型)才是真正核心,BOM提供很多對象,用於訪問瀏覽器的功能,這些功能與任何網頁內容無關。 window對象 location對象 navigator對象 screen對象 history對象 win ...
  • 背景 由於公司的CMS系統里,只接受rar格式壓縮的文件,所以沒法直接使用nodejs里提供的zip壓縮組件。只能從winRar軟體入手了,但網上沒有多少這方面相關的東西,所以下麵也是自己嘗試著在做。 主要解決的幾個問題 rar軟體的位置獲取問題 通過node的命令行組件child_process, ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...