[英]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.