[英]How can i improve my personnal jQuery Dialog plugin
我一直在編寫自己的對話框系統進行練習,並能夠根據需要自定義它。 這是我所做的。
$(function(){
$.fn.window = function(attr){
var $self = this;
if(!attr)
attr = {};
$.extend({
autoOpen:false
}, attr);
/**
* Create the window by updating the current jQuery block
* And adding the required classes
*/
this.create= function(){
// Already created
if($self.hasClass('window-window'))
return;
$self.addClass('window-window');
// Creating the header and appending the title
var $windowHeader = $('<div class="window-header"></div>');
var $title = $self.attr('title');
$windowHeader.html($title);
$windowHeader.append('<div class="loading-item loading-item-footer round-loading25" ' +
'data-loading-item="window" style="display:none"></div>');
// Wrapping content in a window-content class
// So the window has the proper format
$self.children().wrapAll('<div class="window-content"></div>');
$self.prepend($windowHeader);
};
/**
* Open the window in a blackish div
* With the events to close it
*/
this.open = function(){
// Creating the background
var $backgroundDiv = $('<div></div>');
$backgroundDiv.addClass('window-background');
// Making it take the size of the page
$backgroundDiv.height($(window).height());
$backgroundDiv.width($(window).width());
$self.detach().appendTo($backgroundDiv);
// The window is hidden by default, showing it
$self.show();
$('html').prepend($backgroundDiv);
// Handling closing the window
$backgroundDiv.click(function(e){
var $target = $(e.target);
if(!$target.hasClass('window-background'))
return;
$self.hide();
$self.detach().appendTo('html');
$backgroundDiv.remove();
});
};
this.create();
if(attr.autoOpen){
this.open();
}
};
});
現在,我懷疑我是否將窗口從html文檔末尾的本地塊中取出。 我希望將其恢復到他的位置,但是我還不知道該怎么做。 任何想法 ?
首先,創建一個jQuery函數,但是在document.ready $(...)
上執行它。 您應該只創建它,否則在加載文檔之前該功能將無法用於其他代碼。
然后,您希望將窗口插入到與原始元素相同的位置,因為在jQuery中具有insertBefore和insertAfter。 您可以使用prepend,但是會將其插入為$ self的第一個元素。
我敦促您研究一下jQuery的方法鏈,這可能會使您的代碼更具可讀性。 代替:
// Creating the background
var $backgroundDiv = $('<div></div>');
$backgroundDiv.addClass('window-background');
// Making it take the size of the page
$backgroundDiv.height($(window).height());
$backgroundDiv.width($(window).width());
采用
// Creating the background
var $backgroundDiv = $('<div></div>')
.addClass('window-background')
// Making it take the size of the page
.css({
height:$(window).height(),
width:$(window).width()
});
例如。
您還可以使用CSS類來存儲信息,例如是否單擊過某些內容。 也許可以,但是考慮到您可能想要更改CSS類,並且突然之間,代碼的功能與設計緊密相關。 也許使用.data()會更好,即使您添加更多代碼也可以樣式化元素。
您使用.wrap獲取原始內容並將其放在窗口中。 這可能就是您一直以來想要的,但同時也請看一下https://api.jquery.com/clone/ ,它使您可以獲取元素而無需從其原始來源中刪除它們。 同樣,只有它對您更好。
作為最后的建議,請使用http://jsfiddle.net共享您的工作代碼,以便其他人不僅可以對其進行評論,還可以對其進行實際操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.