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){ //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. 在新窗口中打開鏈接
$(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 rel=external>open link</a>
4. 檢測瀏覽器
$(document).ready(function() {// Target Firefox 2 and aboveif ($.browser.mozilla && $.browser.version >= "1.8" ){ // do something}// Target Safariif( $.browser.safari ){ // do something}// Target Chromeif( $.browser.chrome){ // do something}// Target Caminoif( $.browser.camino){ // do something}// Target Operaif( $.browser.opera){ // do something}// Target IE6 and belowif ($.browser.msie && $.browser.version <= 6 ){ // do something}// Target anything above IE6if ($.browser.msie && $.browser.version > 6){ // do something}});
5. 預加載圖片
$(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[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>});
7. 獲得鼠標指針XY值
$(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>});
8.檢查圖片是否加載完成
有時候你需要確保圖片完成加載完成以便執行后面的操作:$('img').load(function () { console.log('image load successful');});
你可以把 img 替換為其他的 ID 或者 class 來檢查指定圖片是否加載完成。
9.自動修改破損圖像
如果你碰巧在你的網站上發現了破碎的圖像鏈接,你可以用一個不易被替換的圖像來代替它們。添加這個簡單的代碼可以節省很多麻煩:
$('img').on('error', function () { $(this).prop('src', 'img/broken.png');});
即使你的網站沒有破碎的圖像鏈接,添加這段代碼也沒有任何害處。
10. jQuery延時加載功能
$(document).ready(function() { window.setTimeout(function() { // do something }, 1000);});
以上就是小編為大家整理的jQuery封裝好的一些常用的操作內容,本文很實用建議大家可以收藏起來,方便在日后使用,希望本文對大家學習jQuery有很好的幫助。
新聞熱點
疑難解答