jquery - 在触发 JQuery 幻灯片之前加载所有图像

标签 jquery css ruby-on-rails

我修改了 Visual Idiot 的 Unslider ( http://unslider.com/ ) 以适应基于图像比例的多宽度幻灯片,但在这个过程中,我遇到了一个错误,导致幻灯片加载为小缩略图(我认为在图像没有完全加载的情况)。那是问题#1。所以我试图等到所有图像都加载完毕。但我还没有找到成功做到这一点的方法。这是问题 #2。

这是我在 Unslider init() 函数中添加的代码:

_.init = function(el, o) {
  //  Check whether we're passing any options in to Unslider
  _.o = $.extend(_.o, o);

  _.el = el;
  _.ul = el.find(_.o.items);
  _.max = [el.outerWidth() | 0, el.outerHeight() | 0];
  _.max = [100, 100];
  _.li = _.ul.find(_.o.item).each(function(index) {
    var me = $(this);
    var an_image = me.find('img');
    an_image.load(function() {
      width = an_image[0].naturalWidth,
      height = an_image[0].naturalHeight;

      setSlideHeight(an_image, width, height, 300, 20);
      if ( an_image.parent().parent().is(":last-child") ) {

        _.el.css("width", 900);
      }
    })  

    //  Set the max values
    //if (width > _.max[0]) _.max[0] = width;
    //if (height > _.max[1]) _.max[1] = height;
  });

这是我的 Ruby 部分,其中包含一个内联脚本,用于在加载所有图像时触发 Unslider。

<% if @page.cap_gallery_images.any? %>
  <script>
    $(document).ready(function() {
      var numLoaded = 0;
      var numToLoad = $('#gallery img').length;
      alert("To Load: " + numToLoad);
      $('#gallery img').load(function(){
        numLoaded += 1;
        alert("Loaded: " + numLoaded);
        if (numLoaded == numToLoad) {
          var gallery = $('#gallery').unslider(),
          data = gallery.data('unslider');
          data.to(0);
        }
      });
      $("#slidecontainer .slide a").click(function(e) {
        destination = $(this).parent().index();
        data.to(destination);
        e.preventDefault;
      });
      $(window).scroll(function() {
        checkGalleryAgainstLogo();
      });
      $(window).resize(function() {
        checkGalleryAgainstLogo();
      });
      checkGalleryAgainstLogo();
      $('#logo.small').addClass('white');
    });
  </script>
<% end %>

问题是图像加载处理程序似乎并未全部触发。在我正在使用它的页面上的上下文中查看它:http://penumbra-2.herokuapp.com/education

最佳答案

关于 #2:我认为你把它搞得太复杂了。您不必像现在这样检查单个 img Assets ;你真的只想知道整个画廊何时加载完毕,所以让你的生活变得简单:

  $('#gallerycontainer').load(function(){
      $('#gallery').unslider();
    }
  });

您可能想将 HTML 添加到您的问题中,以便人们知道如何定位 jQuery:

<div id="gallerycontainer">
  <div id="gallery">
    <div id="slidecontainer">
      <div class="slide">
        <a href="#"><img /></a>
      </div>
    </div>
  </div>
</div>

关于jquery - 在触发 JQuery 幻灯片之前加载所有图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23594794/

相关文章:

javascript - 悬停上的 CSS TABS

html - 将列表项对齐到 ul 容器的顶部

ruby-on-rails - 可以做后无法推送到Heroku

ruby-on-rails - 在具有 ActiveRecord 条件的相关模型中按字段排序

ruby-on-rails - 在 Rails 中记录部分参数

javascript - 使用 ekko-lightbox 旋转图像

php - Chart.js、PHP 和 JSON 循环问题

jquery - 使用 jQuery 在鼠标悬停时向 li 元素的子元素添加类

jQuery翻译+切换,如何链接两者?

容器内的 HTML 复选框标签未按预期显示