【问题标题】:writing a jquery function to reuse a formula编写一个 jquery 函数来重用一个公式
【发布时间】:2011-10-06 14:16:37
【问题描述】:

我有一个函数可以做一些事情,它做的一件事是计算高度/宽度并应用 css 顶部/左侧进行居中。我不想多次重写公式,而是希望能够重用它并通过它传递参数。

我有:

loading.css({
    top: (wrapper.height() - loading.outerHeight()) / 2 + 'px',
    left: (wrapper.width() - loading.outerWidth()) / 2 + 'px'
});

我希望能够重复使用这两个公式,并将loading 替换为其他已注册的元素。

我不知道自己在做什么,我尝试了几件失败的事情......

我希望能够通过 loading._center(); 之类的方式调用它


当函数运行时,它会附加加载 div 并使用上面的代码计算绝对定位 top 和 left。我希望它在窗口调整大小时保持居中,所以我基本上复制了上面的代码并用$(window).resize 函数包装它。

当显示错误 div 时,由于高度/宽度尺寸不同,我正在使用类似的代码再次计算顶部和左侧。而不是复制element.css({top: [...], left: [...]}),我只想做类似...

_center = function() {
    var context = $(this);
    context.css({
        top: (wrapper.height() - context.outerHeight()) / 2 + 'px',
        left: (wrapper.width() - context.outerWidth()) / 2 + 'px'
    });
};

loading._center();

我很接近。我忘了返回计算结果。我现在有:

_center = function($this) {
    $this.css({
        top: (wrapper.height() - $this.outerHeight()) / 2 + 'px',
        left: (wrapper.width() - $this.outerWidth()) / 2 + 'px'
    });
};

_center(loading);

【问题讨论】:

  • 提供更多示例,说明如何重用这些函数

标签: javascript jquery formula reusability


【解决方案1】:

你可以为第二个参数提供一个函数:

loading.css('top', function(index, oldValue) {
  return (wrapper.height() - $(this).outerHeight()) / 2 + 'px';
});

loading.css('left', function(index, oldValue) {
  return (wrapper.width() - $(this).outerWidth()) / 2 + 'px';
});

这是 .css() 的 documentation

【讨论】:

    【解决方案2】:

    您可以将其注册为 jQuery 插件:

    $.fn._center = function(wrapper) {
        return this.each(function() {
            $(this).css({
                top: ($(wrapper).height() - $(this).outerHeight()) / 2 + 'px',
                left: ($(wrapper).width() - $(this).outerWidth()) / 2 + 'px'    
            });
        });
    };
    

    然后这样称呼它:

    var wrapper = $("#someDiv");
    $(".foo, .bar")._center(wrapper);
    

    authoring jQuery plugins.

    【讨论】:

    • 我想我在某处读到了一些插件,这些插件将所有东西分开,使命名空间或其他东西变得混乱。
    • @gavsiu - 您应该阅读上面链接的文档中有关命名空间的部分。
    猜你喜欢
    • 1970-01-01
    • 2018-12-29
    • 2014-05-12
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多