1. 新窗口打開鏈接
XHTML 1.0 Strict 版本不支持 target="_blank" 屬性,而使用 JQuery 能很好地解決這個(gè)問題,實(shí)現(xiàn)新窗口打開網(wǎng)頁:
$('a[@rel$='external']').click(function(){
this.target = "_blank";
});
/*
Usage:
<a rel="external">mangguo.org</a>
*/
2. 獲得匹配元素的總數(shù)
以下代碼將返回匹配元素的數(shù)目:
$('element').size();
3. 預(yù)加載圖像
當(dāng)使用 Javascript 處理圖像載入時(shí),可以使用圖像實(shí)現(xiàn)預(yù)加載:
jQuery.preloadImages = function()
{
for(var i = 0; i").attr("src", arguments[i]);
}
};
// Usage
$.preloadImages("image1.gif", "/path/to/image2.png", "some/image3.jpg");
4. 檢測(cè)瀏覽器
根據(jù)不同瀏覽器加載不同 CSS 能防止因?yàn)g覽器差異造成的樣式表渲染差異,使用 JQuery 可以輕松實(shí)現(xiàn):
//A. Target Safari
if( $.browser.safari ) $("#menu li a").css("padding", "1em 1.2em" );
//B. Target anything above IE6
if ($.browser.msie && $.browser.version > 6 ) $("#menu li a").css("padding", "1em 1.8em" );
//C. Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ) $("#menu li a").css("padding", "1em 1.8em" );
//D. Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ) $("#menu li a").css("padding", "1em 1.8em" );
5. 字符串替換
用 JQuery 能對(duì)文本內(nèi)容中的特定字符串進(jìn)行替換操作:
var el = $('#id');
el.html(el.html().replace(/word/ig, ""));
6. 列高度相等
用 CSS 實(shí)現(xiàn)兩列高度相等并不容易,JQuery 能幫你解決:
function equalHeight(group) {
tallest = 0;
group.each(function() {
thisHeight = $(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}
/*
Usage:
$(document).ready(function() {
equalHeight($(".recent-article"));
equalHeight($(".footer-col"));
});
*/
7. 字體大小重設(shè)
字體大小重設(shè)是一個(gè)非常常用的功能:
$(document).ready(function(){
// Reset Font Size
var originalFontSize = $('html').css('font-size');
$(".resetFont").click(function(){
$('html').css('font-size', originalFontSize);
});
// Increase Font Size
$(".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 Font 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;
});
});
8. 禁用右鍵菜單
有許多 JavaScript 代碼段可禁用右鍵菜單,但 JQuery 使操作變得更容易:
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});