【问题标题】:HTML appending multiple times when window resizes窗口调整大小时多次追加 HTML
【发布时间】:2012-09-07 00:39:30
【问题描述】:

我想为较小的屏幕尺寸附加一些来自变量的 HTML 内容。但是,当我调整浏览器的大小时,内容会附加(应该如此),但如果我继续移动窗口,它会继续附加 HTML 的多个副本。

我怎样才能阻止它这样做?

这就是我正在做的事情:

function adjustStyle(width) {
      width = parseInt(width);
        if (width < 700) {
            $('ul.nav li.top ul.submenu').removeAttr("style");
            $('body').append(str);  // this is when I am having the problem appending

        } else if (width >= 700) {
            $('ul.nav').removeAttr("style");
            $('.form-wrapper').removeAttr("style");
            var toggle = function(direction, display) {
            return function() {
              var self = this;
              var ul = $('ul.submenu', this);
              if( ul.css('display') === display && !self['block' + direction] ) {
                self['block' + direction] = true;
                ul['slide' + direction]('fast', function() {
                  self['block' + direction] = false;
                });
              }
            };
          };
          $('ul.nav li.top').hover(toggle('Down', 'none'), toggle('Up', 'block'));
          $('ul.nav li.top ul.submenu').hide();
          $('#gallery').remove();
        } else {

        }
    }
$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

【问题讨论】:

  • 为什么不使用媒体查询呢?

标签: jquery append media-queries multiple-instances window-resize


【解决方案1】:

您需要debounce 调整大小事件,以便它仅在调整大小完成时触发

这是必需的,因为 -

  • 在 IE、Safari 和 Chrome 中,只要用户继续调整窗口大小,就会触发许多调整大小事件。
  • Opera 使用尽可能多的调整大小事件,但在调整大小结束时全部触发。
  • 尽管如此,Firefox 在调整大小结束时会触发一个调整大小事件。

以下是我对this question 的回答中的一个sn-p。

var resizeTimer = null;    

$(window).resize(function(){

   clearTimeout(resizeTimer); //ignore previous trigger

   resizeTimer= setTimeout(function(){ //wait to execute handler again
     //execute actual handler here
   }, 10);
});

除此之外,我建议你有一个占位符来添加你的内容 -

$('body #appendTarget').html(str); //Since .append() will anyways append multiple times

【讨论】:

    【解决方案2】:

    在您的 adjustStyle 函数中,您可以使用 $(window).off('resize') 删除事件处理程序,或者只使用一个默认为 true 但在第一次运行时设置为 false 的布尔值。

    【讨论】:

      【解决方案3】:

      您正在做的是将值附加到页面,或者只是将它们添加到那里。听起来你想做的只是替换值。使用 .html() 函数代替 .append()。

      【讨论】:

        猜你喜欢
        • 2014-01-14
        • 2022-06-18
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 2019-05-15
        • 1970-01-01
        • 1970-01-01
        • 2012-08-02
        相关资源
        最近更新 更多