jquery ui中的dialog,官網上經典的例子

來源:互聯網
上載者:User

標籤:

jquery ui中dialog和easy ui中的dialog很像,但是最近用到的時候全然沒有印象,一段時間不用就忘記了,這篇隨筆介紹一下這個控制項。

1.執行個體

官網原始碼中給出了一些執行個體,首先看看執行個體是什麼樣子的。

 

a.預設功能

也是最簡單的應用,也就是開啟一個對話方塊,代碼如下

<!doctype html><html lang="en"><head>    <meta charset="utf-8">    <title>jQuery UI Dialog - Default functionality</title>    <link rel="stylesheet" href="../../themes/base/all.css">    <script src="../../external/jquery/jquery.js"></script>    <script src="../../ui/core.js"></script>    <script src="../../ui/widget.js"></script>    <script src="../../ui/mouse.js"></script>    <script src="../../ui/draggable.js"></script>    <script src="../../ui/position.js"></script>    <script src="../../ui/resizable.js"></script>    <script src="../../ui/button.js"></script>    <script src="../../ui/dialog.js"></script>    <link rel="stylesheet" href="../demos.css">    <script>    $(function() {        $( "#dialog" ).dialog();    });    </script></head><body><div id="dialog" title="Basic dialog">    <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></div><div class="demo-description"><p>The basic dialog window is an overlay positioned within the viewport and is protected from page content (like select elements) shining through with an iframe.  It has a title bar and a content area, and can be moved, resized and closed with the ‘x‘ icon by default.</p></div></body></html>

引用了一堆的js檔案,這個與下載的時候選擇的類型有關,可以選擇All jQuery UI Downloads,也可以在當前頁面選擇要用到的組件下載。關鍵代碼$( "#dialog" ).dialog();,載入頁面的時候彈出一個對話方塊。效果如1


圖1

 

b.模態對話方塊

關鍵代碼如下:

    $(function() {        $( "#dialog-message" ).dialog({            modal: true,            buttons: {                Ok: function() {                    $( this ).dialog( "close" );                }            }        });    });

作用是彈出一個模態對話方塊,mode:true,其實就是後面不能回到後面的父頁面,除非關閉當前的對話方塊。在對話方塊後面加了一個OK關閉按鈕,效果如2


圖2

 

c.確認對話方塊

關鍵代碼如下:

    $(function() {        $( "#dialog-confirm" ).dialog({            resizable: false,            height: "auto",            width: 400,            modal: true,            buttons: {                "Delete all items": function() {
            //這裡可以加入一些操作 $( this ).dialog( "close" ); }, Cancel: function() { $( this ).dialog( "close" ); } } }); });

加了兩個按鈕,一個確認,一個取消,可以分別做一些操作,其實也不限於這兩個按鈕,如果需要的話可以在下面添加任意多個按鈕,實現任意多的功能。效果如下如3


圖3

帶form功能的對話方塊

這個例子有些複雜,可以實現驗證,請求等功能,關鍵代碼如下

<!doctype html><html lang="en"><head>    <meta charset="utf-8">    <title>jQuery UI Dialog - Modal form</title>    <link rel="stylesheet" href="../../themes/base/all.css">    <script src="../../external/jquery/jquery.js"></script>    <script src="../../ui/core.js"></script>    <script src="../../ui/widget.js"></script>    <script src="../../ui/mouse.js"></script>    <script src="../../ui/button.js"></script>    <script src="../../ui/draggable.js"></script>    <script src="../../ui/position.js"></script>    <script src="../../ui/resizable.js"></script>    <script src="../../ui/dialog.js"></script>    <script src="../../ui/effect.js"></script>    <link rel="stylesheet" href="../demos.css">    <style>        label, input { display:block; }        input.text { margin-bottom:12px; width:95%; padding: .4em; }        fieldset { padding:0; border:0; margin-top:25px; }        h1 { font-size: 1.2em; margin: .6em 0; }        div#users-contain { width: 350px; margin: 20px 0; }        div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }        div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }        .ui-dialog .ui-state-error { padding: .3em; }        .validateTips { border: 1px solid transparent; padding: 0.3em; }    </style>    <script>    $(function() {        var dialog, form,            // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29            emailRegex = /^[a-zA-Z0-9.!#$%&‘*+\/=?^_`{|}~-][email protected][a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,            name = $( "#name" ),            email = $( "#email" ),            password = $( "#password" ),            allFields = $( [] ).add( name ).add( email ).add( password ),            tips = $( ".validateTips" );        function updateTips( t ) {            tips                .text( t )                .addClass( "ui-state-highlight" );            setTimeout(function() {                tips.removeClass( "ui-state-highlight", 1500 );            }, 500 );        }        function checkLength( o, n, min, max ) {            if ( o.val().length > max || o.val().length < min ) {                o.addClass( "ui-state-error" );                updateTips( "Length of " + n + " must be between " +                    min + " and " + max + "." );                return false;            } else {                return true;            }        }        function checkRegexp( o, regexp, n ) {            if ( !( regexp.test( o.val() ) ) ) {                o.addClass( "ui-state-error" );                updateTips( n );                return false;            } else {                return true;            }        }        function addUser() {            var valid = true;            allFields.removeClass( "ui-state-error" );            valid = valid && checkLength( name, "username", 3, 16 );            valid = valid && checkLength( email, "email", 6, 80 );            valid = valid && checkLength( password, "password", 5, 16 );            valid = valid && checkRegexp( name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter." );            valid = valid && checkRegexp( email, emailRegex, "eg. [email protected]" );            valid = valid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );            if ( valid ) {                $( "#users tbody" ).append( "<tr>" +                    "<td>" + name.val() + "</td>" +                    "<td>" + email.val() + "</td>" +                    "<td>" + password.val() + "</td>" +                "</tr>" );                dialog.dialog( "close" );            }            return valid;        }        dialog = $( "#dialog-form" ).dialog({            autoOpen: false,            height: 400,            width: 350,            modal: true,            buttons: {                "Create an account": addUser,                Cancel: function() {                    dialog.dialog( "close" );                }            },            close: function() {                form[ 0 ].reset();                allFields.removeClass( "ui-state-error" );            }        });        form = dialog.find( "form" ).on( "submit", function( event ) {            event.preventDefault();            addUser();        });        $( "#create-user" ).button().on( "click", function() {            dialog.dialog( "open" );        });    });    </script></head><body><div id="dialog-form" title="Create new user">    <p class="validateTips">All form fields are required.</p>    <form>        <fieldset>            <label for="name">Name</label>            <input type="text" name="name" id="name" value="Jane Smith" class="text ui-widget-content ui-corner-all">            <label for="email">Email</label>            <input type="text" name="email" id="email" value="[email protected]" class="text ui-widget-content ui-corner-all">            <label for="password">Password</label>            <input type="password" name="password" id="password" value="xxxxxxx" class="text ui-widget-content ui-corner-all">            <!-- Allow form submission with keyboard without duplicating the dialog button -->            <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">        </fieldset>    </form></div><div id="users-contain" class="ui-widget">    <h1>Existing Users:</h1>    <table id="users" class="ui-widget ui-widget-content">        <thead>            <tr class="ui-widget-header ">                <th>Name</th>                <th>Email</th>                <th>Password</th>            </tr>        </thead>        <tbody>            <tr>                <td>John Doe</td>                <td>[email protected]</td>                <td>johndoe1</td>            </tr>        </tbody>    </table></div><button id="create-user">Create new user</button><div class="demo-description"><p>Use a modal dialog to require that the user enter data during a multi-step process.  Embed form markup in the content area, set the <code>modal</code> option to true, and specify primary and secondary user actions with the <code>buttons</code> option.</p></div></body></html>

這個是帶請求功能的對話方塊,代碼很嚴謹

var dialog, form,
emailRegex = /^[a-zA-Z0-9.!#$%&‘*+\/=?^_`{|}~-][email protected][a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
name = $( "#name" ),
email = $( "#email" ),
password = $( "#password" ),
allFields = $( [] ).add( name ).add( email ).add( password ),
tips = $( ".validateTips" );

定義元素變數,要用到的驗證,allFields = $( [] ).add( name ).add( email ).add( password ),這個用來把要用到的變數加到集合裡面,用來添加和刪除css樣式,後面會用到的,很巧妙,$( [] )這個寫法可以把多個元素添加到一個集合中。

function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}

給元素添加文字和css樣式,並且在500毫秒內移除這個樣式,不明白.removeClass( "ui-state-highlight", 1500 )後面一個參數1500是什麼意思

function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
}

檢查輸入文字的長短,4個參數分別是元素本身,元素名稱,最小長度,最大長度。

function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}

用Regex檢查元素是否符合規則,3個參數,元素本身,Regex,錯誤提示。

function addUser() {
var valid = true;
allFields.removeClass( "ui-state-error" );

valid = valid && checkLength( name, "username", 3, 16 );
valid = valid && checkLength( email, "email", 6, 80 );
valid = valid && checkLength( password, "password", 5, 16 );

valid = valid && checkRegexp( name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter." );
valid = valid && checkRegexp( email, emailRegex, "eg. [email protected]" );
valid = valid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

if ( valid ) {
$( "#users tbody" ).append( "<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>" );
dialog.dialog( "close" );
}
return valid;
}

添加使用者的方法,驗證方法valid = valid && 這個用的很巧妙,連續利用了&&操作,這裡的寫法非常的靈活也很巧妙。在這裡可以實現具體的功能,也可以在form裡面添加action,form到具體頁面中操作。

dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Create an account": addUser,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});

這裡才是最主要的功能,一個定義一個對話方塊,其中有個2個按鈕,一個是添加一個帳號,訪問addUser函數,一個是取消,直接定義關閉對話方塊,最後還定義了預設的關閉功能,form中清除元素的值,清除錯誤提示。

form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addUser();
});

定義form,其實就是頁面中的form,還定義了提交時請求動作,首先取消預設事件,然後執行addUser。

$( "#create-user" ).button().on( "click", function() {
dialog.dialog( "open" );
});

給添加使用者按鈕綁定事件,這裡綁定事件沒有直接.click,也沒有live,也沒有trigger,on是jquery官方推薦的一個綁定函數方法。注意這裡不是頁面載入的時候就顯示對話方塊,而是點擊添加帳號的時候彈出這個對話方塊,所以要先定義這個對話方塊“dialog = $( "#dialog-form" ).dialog({”,點擊添加按鈕的時候彈出對話方塊“dialog.dialog( "open" );”。

頁面如4


圖4

點擊添加使用者彈出對話方塊5


圖5

元素驗證失敗時6


圖6

這個例子很經典!

d.帶動畫功能的對話方塊

關鍵代碼如下:

    $(function() {        $( "#dialog" ).dialog({            autoOpen: false,            show: {                effect: "blind",                duration: 1000            },            hide: {                effect: "explode",                duration: 1000            }        });        $( "#opener" ).click(function() {            $( "#dialog" ).dialog( "open" );        });    });

定義顯示和影藏效果,effect: "blind":開啟時時百葉窗效果,從上到下顯示,effect: "explode"關閉時是爆發,片段效果。

百葉窗效果如7


圖7

爆炸效果8


圖8

同上,注意這裡不是頁面載入的時候就顯示對話方塊,而是點擊添加帳號的時候彈出這個對話方塊,所以要先定義這個對話方塊“$( "#dialog" ).dialog({,”,點擊添加按鈕的時候彈出對話方塊“dialog.dialog( "open" );”

 

2.屬性,事件,方法

關於屬性,事件和方法內容很多,可以查看中文文檔http://jqueryui.net/dialog/

jquery ui中的dialog,官網上經典的例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.