使用 jQuery 创建多个 div 框
我希望能够通过单击图标来创建类似窗口的框。如果我已经创建了一个并再次单击,则会创建另一个,依此类推。使用我的代码,我可以创建多个框,但内部 div 只能在第一个打开的窗口中创建。这样做的原因是,如果创建了多个盒子,则 div 将具有 id,这当然不是正确的方法。
我实际上有疑问在这里: 1. 如何更改代码以便可以创建多个带有内部 div 的框? 2. 如果我想要一个创建的框与上次创建的框重叠,但向右移动 10 像素,向下移动 10 像素,最好的方法是什么?
谢谢!
代码:
PROGRAM.popup = function(width, height){
this.width = width;
this.height = height;
}
PROGRAM.popup.prototype.buildPopup = function(){
$('<div/>', {
id: 'window',
width: this.width,
height: this.height,
}).appendTo('#container');
$('<div/>', {
id: 'windowTop',
width: this.width,
}).appendTo('#window');
}
...
var popup = new PROGRAM.popup(300, 300);
popup.buildWindow();
var popup2 = new PROGRAM.popup(300, 300);
popup2.buildWindow();
I want to be able to create window like boxes by clicking on an icon. If I've created one and click again, another shall be created and so on. With my code I can create several boxes, but the inner-div only gets created in the first opened window. The reason for this is that if several boxes are created, the divs will have id's, which of course isn't the right way to do it.
I actually have to questions here:
1. How can I change my code so I can create several boxes with inner-divs?
2. What is the best way to do if I want I want a box that gets created to overlap the last created one, but moved 10 px right and 10 px down?
Thanks!
The code:
PROGRAM.popup = function(width, height){
this.width = width;
this.height = height;
}
PROGRAM.popup.prototype.buildPopup = function(){
$('<div/>', {
id: 'window',
width: this.width,
height: this.height,
}).appendTo('#container');
$('<div/>', {
id: 'windowTop',
width: this.width,
}).appendTo('#window');
}
...
var popup = new PROGRAM.popup(300, 300);
popup.buildWindow();
var popup2 = new PROGRAM.popup(300, 300);
popup2.buildWindow();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以删除
window
ID 并将其用作样式的类。您可以将对窗口 div 的引用直接保存到变量中,并在appendTo()
中使用它。检索上一个窗口 div 并使用
offset()
获取其位置。然后根据这些值设置自己的偏移量。JavaScript:
此处是代码。
You can remove the
window
ID and use it as a class for styling. You can save the reference to the window div directly into variable and use it inappendTo()
.Retrieve previous window div and get his position using
offset()
. Then set own offset based on those values.JavaScript:
HERE is the code.
(2)我会这样做:
(2) I will do it this way:
(1) 您或许应该删除 ID 属性。如果您需要以某种方式引用 ID,请从头开始生成它,而不是通过执行以下操作来使用硬编码值:
(2) 当然,最简单的解决方案是绝对定位 div (
position:absolute
)并跟踪其他 div 的位置,以免与它们重叠。不过,这听起来比我想做的还要多。(1) You should probably remove the ID attribute. If you need to reference the ID in some way, generate it from scratch instead of using a hard coded values by doing something like this:
(2) Certainly, the easiest solution would be to position the divs absolutely (
position:absolute
) and keep track of where the other divs are positioned as to not overlap them. That sounds like more work than I'd like to do though.