十條jQuery代碼片段助力Web開發效率提升
以下十項jQuery示例可以幫助大家的Web設計項目順利實現效率提升。
檢測IE瀏覽器
在進行CSS設計時,IE瀏覽器對開發者及設計師而言無疑是個麻煩。盡管IE6的黑暗時代已經過去,IE瀏覽器家族的人氣亦在不斷下滑,但我們仍然有必要對其進行檢測。當然,以下片段亦可用于檢測其它瀏覽器。
$(document).ready(function() { if (navigator.userAgent.match(/msie/i) ){ alert('I am an old fashioned Internet Explorer'); } });
來源: Stack Overflow
平滑滾動至頁面頂部
以下是jQuery最為常見的一種實現效果:點擊一條鏈接以平滑滾動至頁面頂部。雖然沒什么新鮮感可言,但每位開發者幾乎都用得上。
$("a[href='#top']").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; });
來源: Stalk Overflow
保持始終處于頂部
以下代碼片段允許某一元素始終處于頁面頂部。可以想見,其非常適合處理導航菜單、工具欄或者其它重要信息。
$(function(){ var $win = $(window) var $nav = $('.mytoolbar'); var navTop = $('.mytoolbar').length && $('.mytoolbar').offset().top; var isFixed=0; processScroll() $win.on('scroll', processScroll) function processScroll() { var i, scrollTop = $win.scrollTop() if (scrollTop >= navTop && !isFixed) { isFixed = 1 $nav.addClass('subnav-fixed') } else if (scrollTop <= navTop && isFixed) { isFixed = 0 $nav.removeClass('subnav-fixed') } }
來源: DesignBump
替換html標簽
jQuery能夠非常輕松地實現html標簽替換,而這也將為我們帶來更多新的可能。
$('li').replaceWith(function(){ return $("<div />").append($(this).contents()); });
檢測屏幕寬度
現在移動設備的人氣幾乎已經超過了傳統計算機,因此對小型屏幕的尺寸進行檢測就變得非常重要。幸運的是,我們可以利用jQuery輕松實現這項功能。
var responsive_viewport = $(window).width(); /* if is below 481px */ if (responsive_viewport < 481) { alert('Viewport is smaller than 481px.'); } /* end smallest screen */
來源: jQuery Rain
自動修復損壞圖片
如果大家的站點非常龐大而且已經上線數年,那么其中或多或少會出現圖片損壞的情況。這項功能可以檢測損壞圖片并根據我們的選擇加以替換。
$('img').error(function(){ $(this).attr('src', 'img/broken.png'); });
來源: WebDesignerDepot
檢測復制、粘貼與剪切操作
利用jQuery,大家可以非常輕松地檢測到選定元素的復制、粘貼與剪切操作。
$("#textA").bind('copy', function() { $('span').text('copy behaviour detected!') }); $("#textA").bind('paste', function() { $('span').text('paste behaviour detected!') }); $("#textA").bind('cut', function() { $('span').text('cut behaviour detected!') });
來源: Snipplr
自動為外部鏈接添加target=“blank”屬性
在鏈接至外部站點時,大家可能希望使用target="blank"屬性以確保在新的選項卡中打開頁面。問題在于,target="blank"屬性并未經過W3C認證。jQuery能夠幫上大忙:以下片段能夠檢測當前鏈接是否指向外部,如果是則自動為其添加target="blank"屬性。
var root = location.protocol + '//' + location.host; $('a').not(':contains(root)').click(function(){ this.target = "_blank"; });
來源: jQuery Rain
懸停時淡入/淡出
又是另一項“經典”效果,大家可以利用以下片段隨時加以運用。
$(document).ready(function(){ $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads $(".thumbs img").hover(function(){ $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover },function(){ $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout }); });
來源: Snipplr
禁用文本/密碼輸入中的空格
無論是電子郵件、用戶名還是密碼,很多常見字段都不需要使用空格。以下代碼能夠輕松禁用選定輸入內容中的全部空格。
$('input.nospace').keydown(function(e) { if (e.keyCode == 32) { return false; } });