線上體驗:https://hovertree.com/texiao/jqueryui/1/
這裡示範第一種做法,另外還有使用 iframe 的版本,見文末連結。
完整程式碼:
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI 打開網址的對話框</title>
<link rel="stylesheet" href="https://hovertree.com/jqueryui/jquery-ui.min.css" />
<script type="text/javascript" src="https://down.hovertree.com/jquery/jquery-1.12.4.min.js"></script>
<script src="https://hovertree.com/jqueryui/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(".hovertreeopen").click(function () {
$.get($(".hovertreeopen").attr("href"), function (result) {
$("#hovertreeurl").html(result);
$('#hovertreeurl').dialog({
width: 600, height: 400, modal: true
});
});
return false;
});
})
</script>
<style type="text/css">
#hovertreeurl { display: none; }
a { color: blue; }
</style>
</head>
<body>
<div style="width:338px;height:100px;margin:50px auto;">
<a href="https://hovertree.com/texiao/hewenqi/" target="_self" class="hovertreeopen">點我</a>
<br />這是一個連結,使用 jQuery UI,點擊時會彈出對話框,內容是連結頁面的內容。關閉對話框後才能操作頁面其他部分。
</div>>
<div id="hovertreeurl" title="div 層對話框">
<p>This is the default dialog which is useful for displaying information.
The dialog window can be moved, resized and closed with the 'x' icon.</p>
<p>這是一個彈出 div 層對話框,可用於顯示資訊。可以拖動、關閉,也可以改變大小。</p>
</div>
<div style="max-width:960px;margin:0px auto;">
<a href="https://hovertree.com/" target="_blank">何問起</a>
</div>
</body>
</html>
第二種 iframe 版本:https://hovertree.com/texiao/jqueryui/1/1.htm
兩種做法的取捨
上面這版是用 $.get 把目標頁面的 HTML 抓回來,塞進 div 再交給 dialog() 包裝。它的優點是內容真正進入了目前頁面的 DOM,可以繼承主頁的樣式,也能被主頁的 JavaScript 操作;缺點是 ajax 有同源限制,跨網域抓取會失敗,而且目標頁若帶有自己的 CSS,樣式可能與主頁互相污染。
iframe 版本則把隔離做得徹底:目標頁在獨立文件環境中執行,樣式與腳本互不干擾,也不受同源問題影響(除非你要跨 frame 讀寫內容)。代價是高度需要自行調整,行動裝置上的捲動體驗也較差。
選擇標準很簡單:內容來自同站、需要與主頁互動,用 ajax;內容來自外部或本身就是完整頁面,用 iframe。
另外提醒 modal: true 這行的意義——它會加上遮罩並阻擋背景互動。若業務上不需要強制性,把它移除會讓使用者自在得多,因為強制性的彈出層在手機小螢幕上特別容易造成操作困擾。
延伸參考:https://hovertree.com/a/bjac/j4kedhuq.htm