DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> 網頁特效代碼
用 HoverTreeShow 外掛彈出遮罩層檢視大圖
編輯:網頁特效代碼     

在開發 HoverTreeTop 專案的產品展示功能時,需要讓使用者點擊縮圖後看到大圖,於是寫了 jQuery 外掛 HoverTreeShow,如今已實際用在專案裡。

線上體驗:https://hovertree.com/texiao/hovertreeshow/

HoverTreeTop 的產品展示頁也是實例:https://hovertree.com/top/htpro/5dbcb599663b3397.htm

彈出後可點擊右上角的 X 關閉,也可以雙擊頁面關閉。

最小使用範例

只要引入一個 CSS、一個 JS,然後在 img 外層包上對應 class 即可:

<link href="https://hovertree.com/texiao/hovertreeshow/hovertreeshow.css" rel="stylesheet" />
<script src="https://hovertree.com/texiao/hovertreeshow/hovertreeshow.js"></script>

<div class="hovertreeshow">
 <img src='example.jpg' />
</div>

完整程式碼:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>使用 HoverTreeShow 外掛彈出圖片大圖層</title>
<meta charset="utf-8" />
<link href="https://hovertree.com/texiao/hovertreeshow/hovertreeshow.css" rel="stylesheet" />
<script src="https://down.hovertree.com/jquery/jquery-1.12.1.min.js"></script>
<style>
#hovertreeshow { width: 400px; height: 400px; overflow: scroll; margin: 5px auto; }
#hovertreeshow img { max-height: 100%; }
#headhovertree { margin: 5px auto; width: 400px; }
a { color: blue; }
</style>
</head>
<body>

<div id="headhovertree">
 <h3>使用 HoverTreeShow 外掛彈出圖片大圖層</h3>
 請點擊下方圖片,將彈出遮罩層顯示原圖。
 <a href="https://hovertree.com/">首頁</a>
</div>

<div id="hovertreeshow" class="hovertreeshow">
 <img src='example1.jpg' />
 <img src='example2.jpg' />
 <img src='example3.gif' />
</div>

<div style="height:600px;width:100%"></div>

<script src="https://hovertree.com/texiao/hovertreeshow/hovertreeshow.js"></script>
</body>
</html>

這裡有個順序上的細節值得注意:CSS 與 jQuery 放在 head,而外掛的 JS 放在 body 尾端。這是因為外掛需要查詢 .hovertreeshow 元素來綁定事件,若放在 head 執行時 DOM 尚未建立,會找不到任何節點而靜默失效。另一個等效做法是把它包在 $(function(){...}) 裡等 DOM ready,兩者擇一即可。

此外,範例中間刻意插入一個 600px 高的空白 div,目的是把頁面撐長、讓捲軸出現,這樣才能驗證遮罩層在頁面捲動後是否仍正確覆蓋整個視窗。這類測試用的佔位元素在正式專案中記得移除。

HoverTreeTop 是一個 ASP.NET 開源的企業網站建置專案,內含 HoverTreeShow 的原始碼,需要的朋友可以下載:https://hovertree.com/h/bjaf/hv6cqe5n.htm

最後補一個實務上的提醒:這類 lightbox 效果的無障礙成本不低。彈出時應該把焦點移進彈出層、鎖定背景捲動、並讓 Esc 鍵可以關閉,關閉後焦點要還回原本的縮圖;同時彈出層需要適當的 role 與 aria 標記,螢幕閱讀器才會正確朗讀。若專案對無障礙有要求,直接採用成熟的 lightbox 套件會比自己維護省下不少功夫。

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