jQuery 函数在调整窗口大小之前不会触发

jQuery functions not firing until you resize window

本文关键字:函数 调整 窗口大小 jQuery      更新时间:2023-09-26

>我有一个基础轨道图像滑块,在您调整浏览器窗口大小之前不会显示。该空间是空的,直到您甚至只是将窗口大小更改一个像素。基金会正在动态计算滑块的高度,但是当页面首次加载时,容器上没有设置高度。

还有一个导航栏,在我调整窗口大小之前,它不会自行更正为计算的宽度。

以下是导航条形码:

Ew.ApplicationView = Ember.View.extend({
  didInsertElement: function() {
    $(".nav").width($(window).width() - 406);
    $(".subnav").width($(window).width() - 396);
    return $(window).resize(function() {
      $(".nav").width($(window).width() - 406);
      return $(".subnav").width($(window).width() - 396);
    });
  }
});

和滑块初始化代码:

Ew.OrbitSliderComponent = Ember.Component.extend({
  initOrbit: function() {
    $(document).foundation('orbit', {
      stack_on_small: true;
      navigation_arrows: false;
      variable_height: true;
    });
  }.on('didInsertElement')
});

是什么原因导致 jQuery 函数在窗口调整大小之前不触发?

一个简单的

技巧是将.resize()函数链接两次:

return $(window).resize(function() {
    $(".nav").width($(window).width() - 406);
    return $(".subnav").width($(window).width() - 396);
}).resize();    // Resize() onload

您可以看到不链接 (http://jsfiddle.net/teddyrised/2x42Q/2/) 和带链接 (http://jsfiddle.net/teddyrised/2x42Q/1) 之间的区别

我不完全明白为什么会发生这种情况,但这似乎与大小有关.nav.subnav对吧?我认为这些元素的初始大小调整发生得太早了。请尝试以下操作:

Ew.ApplicationView = Ember.View.extend({
  didInsertElement: function() {
    Ember.run.scheduleOnce('afterRender', this, function(){
      $(".nav").width($(window).width() - 406);
      $(".subnav").width($(window).width() - 396);
      return $(window).resize(function() {
        $(".nav").width($(window).width() - 406);
        return $(".subnav").width($(window).width() - 396);
      });
    }
  }
});

这使您的逻辑在 Ember 执行完所有渲染内容后运行。实际上,DidInsertElement 只是保证在给定视图的根元素存在时执行。子元素或子视图不必存在!看看我的博客,了解解释和更优雅的方法,以避免代码中这种没有吸引力的嵌套。

可能是部分

在说:

   return $(window).resize(function() {

如果不是 $(window).resize 而是 $(document).load 怎么办?

来自jQuery文档:

/*The load event is sent to an element when it and all sub-elements have been 
completely  loaded. This event can be sent to any element associated with a 
URL: images, scripts, frames, iframes, and the window object.*/