下面這些技巧實現的效果雖不算新鮮,但透過jQuery的封裝,HTML變得異常清爽。簡潔高效的代碼,往往是開發者醉心追求的目標——也許它簡單,能量卻不小。一起來看看這五個非常實用的jQuery技巧。
1. 禁用滑鼠右鍵
$(document).ready(function() { $(document).bind("contextmenu", function(e) { return false; }); });當然,jQuery 1.7以後更推薦用 on() 來代替 bind()。
2. 讓內容閃爍起來
$.fn.flash = function(color, duration) { var current = this.css('color'); this.animate( {color: 'rgb(' + color + ')'}, duration / 2); this.animate( {color: current}, duration / 2); } $('#someid').flash('255,0,0', 1000);3. DOM加載完成的簡寫形式
$(function() { // document is ready.. })4. 探測瀏覽器
// Safari if( $.browser.safari ) { //do something } //Above IE6 if ($.browser.msie && $.browser.version > 6 ) { //do something } // IE6 and below if ($.browser.msie && $.browser.version < 6 ) { //do something } // Firefox 2 and above if ($.browser.mozilla && $.browser.version >= "1.8" ) { //do something }5. 判斷元素是否存在
if($("#someDiv").length) { // yes it does, do something... }以上就是這五個實用的jQuery小技巧,希望對你有所幫助。