今天在 Now you see me… show/hide performance 一文中,看到該文作者分析了各種jQuery顯示、隱藏的作法及其效能比較,最後還提到了一個非常有趣的好方法,他利用禁用、啟用<style>元素的方法來達到套用顯示、隱藏效果,在頁面中需要大量套用情況下效能特別好。

首先利用<style>來定義樣式為隱藏:

<style id="special_hide">
	.special_hide {	display: none;}
</style>

接著在將該<style>元素的disabled屬性設為true使其失去作用,也就是讓他變為顯示,例如jQuery中可以這麼寫:

 $('#special_hide').attr('disabled', true);  // 禁用指定<style>元素

 $('#special_hide').attr('disabled', false); // 啟用指定<style>元素

以下為完整的範例

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
	</script>
	<script type="text/javascript">
	$(function (){
		$('#disableBtn').click(function(){
			$('#special_hide').attr('disabled', true); // 禁用樣式
		});

		$('#enableBtn').click(function(){
			$('#special_hide').attr('disabled', false); // 啟用樣式
		});
	});
	</script>

    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style id="special_hide">.special_hide { display: none; }</style>
  </head>
  <body>

    <button id="disableBtn">取消樣式</button>
    <button id="enableBtn">啟用樣式</button>

    <div class="special_hide">這個元素預設會因為樣式而隱藏</div>

  </body>
</html>

執行範例:

延伸思考

透過禁用、啟用<style>元素的方法,不只可以應用在大量套用顯示、隱藏效果,其實很多效果都可以利用此方法來完成,特別是大量套用時,因為瀏覽器原生的CSS Selector解析,理論上總是會比jQuery Selector來的快。

參考文章

Tagged : , , , ,

你可能會感興趣

“有趣的 jQuery 快速顯示隱藏元素技巧” 目前共有 4 則迴響

  1. 這方法似乎在 chrome 下是無效的

  2. 還是增、刪樣式比較直接。

留下迴響





*