Jquery插件:如何使用窗口调整大小?

时间:2013-10-04 19:32:13

标签: jquery

寻找创建我的第一个Jquery插件。 基本上垂直居中于空白页面中的div。

    (function($){  
    $.fn.centerdiv = function(options) {  
        var defaults = {  
            ratio   :   2
        };
        var options = $.extend(defaults, options);
        // get some useful variables
        var $this           = $(this);
        var $heightDiv      = $this.height();
        var $heightWindow   = $(window).height();
        var $marginTop      = Math.round(($heightWindow - $heightDiv)/options.ratio);
        var applyMargin     = function() {
            $this.css('margin-top',$marginTop+'px');
            console.log($heightWindow);
        }
        $(window).resize(applyMargin);
        applyMargin();
        return $this;
    }; // fn.centerdiv
})(jQuery);

它适用但不适用于“窗口调整大小”。找到另一个答案(jQuery $(window).resize not firing within jQuery plugin),但在$之后添加“窗口”并不能解决我的问题。如何使用此窗口调整大小的插件?谢谢大家!

编辑回答......

3 个答案:

答案 0 :(得分:2)

这里有两个问题

  • 您正在将css应用于window
  • 您的代码部分位于return声明之后。

替换

return this.each(function() {
     $(this).css('margin-top',$marginTop+'px');
}); // return
$(window).resize(function() {
     $(this).css('margin-top',$marginTop+'px');
});

var $this = $(this), f = function(){
    $this.css('margin-top',$marginTop+'px');
}
$(window).resize(f);
f();
return $this;

并将其放在return语句之前。

答案 1 :(得分:2)

this事件处理程序的上下文中的

window.resize引用window。您应该存储对外部this的引用,以便您可以在事件处理程序中使用它:

...
var $this = $(this);
    $(window).resize(function() {
        $this.css('margin-top',$marginTop+'px');
    });
...

您还需要将return放在函数的末尾,不执行后的所有内容。

答案 2 :(得分:0)

解决:我没有重新计算窗口的高度。这是最终的代码。你认为这是对的吗?

(function($){  
    $.fn.centerdiv = function(options) {  
        var defaults = {  
            ratio   :   2
        };
        var options = $.extend(defaults, options);
        // get some useful variables
        var $this           = $(this);
        var calculateMargin = function() {
            var $heightDiv      = $this.height();
            var $heightWindow   = $(window).height();
            var $marginTop      = Math.round(($heightWindow - $heightDiv)/options.ratio);
            return $marginTop;  
        }
        return this.each(function() {
            var $marginTop = calculateMargin();
            $this.css('margin-top',$marginTop+'px');
            $(window).resize(function() {
                var $marginTop = calculateMargin();
                $this.css('margin-top',$marginTop+'px');
            });
        }); 
    }; // fn.centerdiv
})(jQuery);
相关问题