DIV CSS 佈局教程網

用 jQuery 讓彈出視窗跟著按鈕跑:dialog 定位實作
編輯:JQuery特效代碼     

預設的 dialog 一律開在畫面正中央,但有些介面(例如工具列上的小按鈕)會希望對話框緊貼著觸發點跳出來,靠近滑鼠點擊的位置。要達到這個效果,關鍵是先用 offset() 取得元素的座標,再把它餵給 position。

頁面結構

<asp:TextBox ID="tbOperation2" runat="server" onclick="buttonclick($(this))"
    CssClass="ui-button-icons-only" Text="按鈕"></asp:TextBox>

<div id="editdialog" title="Basic dialog">
  <div><label onclick="clickEdit();"  class="labelbutton">Edit</label></div>
  <div><label onclick="clickView();"  class="labelbutton">View</label></div>
  <div><label onclick="clickBuild();" class="labelbutton">Build</label></div>
</div>

初始化

<script type="text/javascript">
var staticsignal;
$(function() {
    // 把 TextBox 套上 jQuery UI 的按鈕樣式
    $(":input.ui-button-icons-only").button();
});
</script>

定位的核心邏輯

<script type="text/javascript">
function buttonclick(e)
{
    var offset = e.offset();   // 取得目前元素的 offset
    var x = offset.left;
    var y = offset.top;

    $("#editdialog").dialog({
        autoOpen   : true,
        draggable  : true,
        resizable  : false,
        position   : [x, y + 35],   // 設定座標,往下偏移避開按鈕本身
        width      : 150
    });

    $(".ui-dialog-titlebar").hide();          // 隱藏標題列
    $('a.ui-dialog-titlebar-close').hide();   // 隱藏關閉鈕
    staticsignal = e;
}
</script>

概念其實很單純:offset() 回傳 { top, left },把它轉成 position 需要的 [x, y] 陣列即可。加上的那個 y + 35 只是為了讓視窗落在按鈕下方而非蓋住它,實際要偏移多少可依版面調整。

兩個容易忽略的細節

第一,position 除了接受座標陣列,也可以傳字串如 'center'、'top',或用 { my: "left top", at: "left bottom", of: element } 這種對齊語法——後者能讓 jQuery UI 自動計算位置,比手動算座標更省心,也更禁得起視窗縮放。

第二,staticsignal = e 把觸發來源記了下來,這是為了後續在 dialog 內的 Edit / View / Build 事件中知道「目前操作的是哪一列」。少了這一步,對話框裡的動作就會失去上下文。

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