首頁  >  文章  >  web前端  >  七個不允許錯過的jQuery小技巧_jquery

七個不允許錯過的jQuery小技巧_jquery

WBOY
WBOY原創
2016-05-16 15:24:211788瀏覽

jQuery是一款輕量級的JavaScript庫,是最受歡迎的客戶端HTML腳本之一,它在WEB設計師和開發者中非常的有名,並且有非常多有用的插件和技術。

本文我們將為大家分享一些jQuery小技巧:

一、在新視窗開啟連結

用下面的程式碼,你點擊連結即可在新視窗開啟:

$(document).ready(function() {
  //select all anchor tags that have http in the href
  //and apply the target=_blank
  $("a[href^='http']").attr('target','_blank');
});

二、設定等高的欄位

應用下面的程式碼,可以讓你的WEB應用每一列高度都想等:

<div class="equalHeight" style="border:1px solid">
  <p>First Line</p>
  <p>Second Line</p>
  <p>Third Line</p>
</div>
<div class="equalHeight" style="border:1px solid">
  <p>Column Two</p>
</div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  equalHeight('.equalHeight');
});
//global variable, this will store the highest height value
var maxHeight = 0;

function equalHeight(col) {
  //Get all the element with class = col
  col = $(col);
  //Loop all the col
  col.each(function() {
    //Store the highest value
    if ($(this).height() > maxHeight) {
      maxHeight = $(this).height();
    }
  });
  //Set the height
  col.height(maxHeight);
}
</script>

三、jQuery預載圖片

這個小技巧可以提升頁面載入圖片的速度:

jQuery.preloadImagesInWebPage = function() {
  for (var ctr = 0; ctr & lt; arguments.length; ctr++) {
    jQuery("").attr("src", arguments[ctr]);
  }
}

// 使用方法:
$.preloadImages("image1.gif", "image2.gif", "image3.gif");

// 检查图片是否被加载
$('#imageObject').attr('src', 'image1.gif').load(function() {
  alert('The image has been loaded…');
});

四、停用滑鼠右鍵

$(document).ready(function() {
  //catch the right-click context menu
  $(document).bind("contextmenu", function(e) {
    //warning prompt - optional
    alert("No right-clicking!");

    //delete the default context menu
    return false;
  });
});

五、設定計時器

$(document).ready(function() {
  window.setTimeout(function() {
    // some code
  }, 500);
});

六、計算子元素的個數

<div id="foo">
  <div id="bar"></div>
  <div id="baz">
    <div id="biz"></div>
    <span><span></span></span>
  </div>
</div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
  //jQuery code to count child elements $("#foo > div").size()
alert($("#foo > div").size())
</script>

七、把元素定位到頁中間

<div id="foo" style="width:200px;height: 200px;background: #ccc;"></div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
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;
}
//Use the above function as:
$('#foo').center();
</script>

讀到這裡的朋友就知道你沒有錯過學習的機會,把這些小技巧累積起來,一定會幫助大家設計出有創意和精美的Web頁面。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn