【问题标题】:Create several div boxes with jQuery使用 jQuery 创建多个 div 框
【发布时间】:2023-03-13 17:40:02
【问题描述】:

我希望能够通过单击图标来创建类似于框的窗口。如果我创建了一个并再次单击,则应创建另一个,依此类推。使用我的代码,我可以创建多个框,但内部 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();

【问题讨论】:

    标签: jquery dom object


    【解决方案1】:
    1. 您可以删除window ID 并将其用作样式类。您可以将对窗口 div 的引用直接保存到变量中,并在 appendTo() 中使用。

    2. 检索前一个窗口 div 并使用offset() 获取他的位置。然后根据这些值设置自己的偏移量。

    JavaScript:

    PROGRAM.popup = function(width, height){
        this.width = width;
        this.height = height;
    };
    
    PROGRAM.popup.prototype.buildPopup = function(){
    
      // save reference to the created div
      // this way we don't have to look for it in DOM
      var win = $('<div/>', {
        'class': 'window',
        'width': this.width,
        'height': this.height
      }).appendTo('#container');
    
      // try to retrieve previous closest sibling with class "window"
      var prev = win.prev('.window');
      // if it exists then get his position and set our based on it
      if (prev.length) {
        win.offset({ 
          left: prev.offset().left + 10, 
          top:  prev.offset().top + 10 });
      }
    
      // nothing changed here
      $('<div/>', {
        'class': 'inner',
        'width': this.width
      }).appendTo(win);
    
    };   
    

    HERE 是代码。

    【讨论】:

      【解决方案2】:

      (2) 我会这样做:

      .mybox{
         padding-top: 10px;
         padding-left: 10px;
      }
      <script>
          var myHtml = '<div class="mybox"><a class="iconAction">icon</a></div>";
          $('body').append(myHtml);
          $('body').on('click', 'a.iconAction',function(event){
             $(this).parent().append(myHtml)
          })
      </script>
      

      【讨论】:

        【解决方案3】:

        (1) 您可能应该删除 ID 属性。如果您需要以某种方式引用 ID,请从头开始生成它,而不是通过执行以下操作使用硬编码值:

        function generateId(){
            var count = 0;
            while(document.getElementById(id = 'anonymous_element_' + (count++))){}
            return id;
        }
        

        (2) 当然,最简单的解决方案是绝对定位 div (position:absolute) 并跟踪其他 div 的位置以免与它们重叠。不过,这听起来比我想做的工作还要多。

        【讨论】:

          猜你喜欢
          • 2019-07-08
          • 1970-01-01
          • 2013-09-01
          • 2014-09-04
          • 2018-01-20
          • 2022-11-11
          • 1970-01-01
          • 2012-07-29
          • 1970-01-01
          相关资源
          最近更新 更多