DIV CSS 佈局教程網

jQuery 實用小技巧 26 連發:禁止右鍵、預載圖片到自訂選擇器
編輯:JQuery特效代碼     

這份清單涵蓋日常開發最常遇到的小需求:禁止右鍵選單、搜尋框提示文字、外部連結新窗開啟、瀏覽器偵測、圖片預載、樣式主題切換、欄位等高、動態調整字級、滑鼠座標、元素替換、延遲載入、無衝突模式等等。

1. 禁止右鍵選單

$(document).ready(function () {
    $(document).bind("contextmenu", function (e) {
        return false;
    });
});

2. 搜尋框提示文字(聚焦即清空)

$(document).ready(function () {
    $("input.text1").val("Enter your search text here");
    textFill($('input.text1'));
});

function textFill(input) {
    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. 讓外部連結在新視窗開啟

$(document).ready(function () {
    // 例一:所有 http 開頭的連結都開新視窗
    $('a[href^="https://"]').attr("target", "_blank");

    // 例二:只有帶 rel="external" 的才開新視窗
    $('a[@rel$='external']').click(function () {
        this.target = "_blank";
    });
});

// 用法
// <A href="https://www.opensourcehunter.com" rel="external">open link</A>

注意:新舊版 jQuery 的屬性選擇器語法不同,1.3 之後 @ 前綴已移除,應寫成 a[rel$='external']。

4. 偵測瀏覽器

jQuery 1.4 中 $.support 逐步取代 $.browser,而 1.9 之後 $.browser 已完全移除。

$(document).ready(function () {
    if ($.browser.mozilla && $.browser.version >= "1.8") { /* Firefox 2+ */ }
    if ($.browser.safari)  { /* Safari  */ }
    if ($.browser.chrome)  { /* Chrome  */ }
    if ($.browser.camino)  { /* Camino  */ }
    if ($.browser.opera)   { /* Opera   */ }
    if ($.browser.msie && $.browser.version <= 6) { /* IE6 及以下 */ }
    if ($.browser.msie && $.browser.version > 6)  { /* IE7 以上    */ }
});

5. 預載圖片

$(document).ready(function () {
    jQuery.preloadImages = function () {
        for (var i = 0; i < arguments.length; i++) {
            $("<img>").attr("src", arguments[i]);
        }
    };
    // 用法
    $.preloadImages("image1.jpg", "image2.jpg");
});

6. 切換頁面樣式主題

$(document).ready(function () {
    $("a.Styleswitcher").click(function () {
        // 用連結的 rel 值去換掉 stylesheet 的 href
        $('link[rel=stylesheet]').attr('href', $(this).attr('rel'));
    });
});

// 頁首
// <LINK href="default.css" type="text/css" rel="stylesheet">

// 切換連結
// <A class="Styleswitcher" href="#" rel="default.css">Default Theme</A>
// <A class="Styleswitcher" href="#" rel="red.css">Red Theme</A>
// <A class="Styleswitcher" href="#" rel="blue.css">Blue Theme</A>

7. 讓兩欄等高

$(document).ready(function () {
    function equalHeight(group) {
        var tallest = 0;
        group.each(function () {
            var thisHeight = $(this).height();
            if (thisHeight > tallest) { tallest = thisHeight; }
        });
        group.height(tallest);
    }
    equalHeight($(".left"));
    equalHeight($(".right"));
});

實務上更建議用 CSS Flexbox 或 Grid 解決等高問題,JS 方案在字型載入完成後可能還需要重算一次。

8. 動態調整頁面字級

$(document).ready(function () {
    var originalFontSize = $('html').css('font-size');

    $(".resetFont").click(function () {
        $('html').css('font-size', originalFontSize);
    });

    $(".increaseFont").click(function () {
        var current = parseFloat($('html').css('font-size'), 10);
        $('html').css('font-size', current * 1.2);
        return false;
    });

    $(".decreaseFont").click(function () {
        var current = parseFloat($('html').css('font-size'), 10);
        $('html').css('font-size', current * 0.8);
        return false;
    });
});

9. 平滑捲動回頂部

$(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;
            }
        }
    });
});

// 用法
// <A name="top"></A>
// <A href="#top">go to top</A>

10. 取得滑鼠座標

$(document).ready(function () {
    $().mousemove(function (e) {
        $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
    });
});
// <DIV id="XY"></DIV>

11. 判斷元素內容是否為空

if ($('#id').html()) { /* 有內容 */ }

12. 替換元素

$('#id').replaceWith('<DIV>I have been replaced</DIV>');

13. 延遲執行

window.setTimeout(function () {
    // do something
}, 1000);

14. 移除文字中的特定單字

var el = $('#id');
el.html(el.html().replace(/word/ig, ""));

15. 判斷元素是否存在於集合中

if ($('#id').length) { /* 存在 */ }

16. 讓整個 DIV 可點擊

$("div").click(function () {
    window.location = $(this).find("a").attr("href");
    return false;
});
// <DIV><A href="index.html">home</A></DIV>

無障礙提醒:這種做法讓鍵盤使用者無法聚焦,比較好的方式是保留 <a> 語意,再用 CSS 把連結的點擊範圍撐滿整個容器。

17. 視窗尺寸改變時切換 class

$(document).ready(function () {
    function checkWindowSize() {
        if ($(window).width() > 1200) { $('body').addClass('large'); }
        else                         { $('body').removeClass('large'); }
    }
    $(window).resize(checkWindowSize);
});

18. 複製元素

var cloned = $('#id').clone();
// <DIV id="id"></DIV>

19. 元素置中於畫面

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();

20. 自訂選擇器

$.extend($.expr[':'], {
    moreThen1000px: function (a) {
        return $(a).width() > 1000;
    }
});

$('.box:moreThen1000px').click(function () {
    alert('The element that you have clicked is over 1000 pixels wide');
});

21. 統計元素數量

$("p").size();     // 亦可寫成 $("p").length

22. 自訂項目符號

$("ul").addClass("Replaced");
$("ul > li").prepend("&#8210; ");

/* ul.Replaced { list-style: none; } */

23. 使用 Google 託管的 jQuery

// 例一:透過 jsapi 載入
<SCRIPT src="https://www.google.com/jsapi"></SCRIPT>
<SCRIPT type="text/javascript">
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function () { /* do something */ });
</SCRIPT>

// 例二:直接引用(最快最省事)
<SCRIPT src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"
        type="text/javascript"></SCRIPT>

24. 關閉所有動畫效果

jQuery.fx.off = true;

除錯或做為使用者偏好設定時很好用,也能省下低階裝置的運算資源。

25. 與其他 JS 庫的 $ 衝突

var $jq = jQuery.noConflict();
$jq('#id').show();

26. 用 load() 做頁面載入提示

先寫好絕對定位在右上角的提示框:

#loading {
    position: absolute; z-index: 900; text-align: center;
    background-color: #eef2fa; border: 1px solid #d8e3e8;
    color: #000; font-size: 12px; padding: 3px; width: 80px;
    right: 0; top: 0;
}

再在所有圖片載入完成後把它藏起來:

<script>
jQuery(document).ready(function ($) {
    $('img').load(function () {
        $('#loading').css("display", "none");
    });
});
</script>

<div id="loading">Loading ...</div>

這裡有個常見陷阱:$('img').load() 只對「已經掛上監聽之後才載入」的圖片有效。若圖片在 ready 觸發前就載完了,回呼永遠不會執行,提示框會一直卡在那裡。實務上建議改用 $(window).load() 或在每張圖上檢查 img.complete。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved