2016-03-15 67 views
0

我目前正在使用無插件創建純jQuery傳送帶。使用jQuery調整傳送帶內div的大小

我被告知添加一個智能調整大小的jQuery事件處理程序是一個很好的方法來做到這一點。但是,我只是不知道如何將它集成到我創建的插件中。

它目前使用$(window).width方法來確定li(picture_slide)的大小,並且由於存在3個圖像,ul(.slider)寬度爲$(window).width * 3。

但是,任何時候我嘗試調整它的圖像適合屏幕,但動畫似乎並沒有工作。

這是我所創建的插件工作,但不調整

; 
(function($, window, document, undefined) { 
"use strict"; 
var pluginName = "chrisCarousel", 
    defaults = { 
     rotationSpeed: 1000, 
     screenTime: 1000 
    }; 

function Plugin(element, options) { 
    this.element = element; 
    this.settings = $.extend(defaults, {}, options); 
    this._defaults = defaults; 
    this._name = pluginName; 
    this.init(); 
} 

$.extend(Plugin.prototype, { 
    init: function() { 
     this.myCarousel(); 
    }, 

    myCarousel: function() { 
    var y = $(window).width(); 

     var t = setInterval(function() { 
      $("#my_carousel ul").animate({marginLeft: - y }, defaults.rotationSpeed, function() { 
       $(this).find(".picture_slide:last").after($(this).find(".picture_slide:first")); 
       $(this).css({marginLeft: 0}); 
      }) 
     }, defaults.screenTime); 
     $(".picture_slide").css("width", y); 
     $(".slider").css("width", y * 3);  
    } 
}); 

$.fn[ pluginName ] = function(options) { 
    return this.each(function() { 
     if (!$.data(this, "plugin_" + pluginName)) { 
      $.data(this, "plugin_" + 
       pluginName, new Plugin(this, options)); 
     } 
    }); 
}; 

})(jQuery, window, document); 

這裏是我被告知要檢查出的智能調整大小: http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/

回答

0

當你調整大小屏幕上,您不會更改y的值。這意味着它仍然具有舊窗口大小的值,這會導致動畫動畫顯示錯誤的寬度。

我建議讓y成爲全局變量,並使用它在用戶調整大小時重新計算y的值。

$(window).on('resize', function(e) { 
    y = $(window).width(); 
});