我有一个函数可以做一些事情,它做的一件事是计算高度/宽度并应用 css top/left 居中。我不想多次重写公式,而是希望能够重用它并通过它传递参数。
我有:
loading.css({
top: (wrapper.height() - loading.outerHeight()) / 2 + 'px',
left: (wrapper.width() - loading.outerWidth()) / 2 + 'px'
});
我希望能够重用这 2 个公式,并将 loading
替换为其他已注册的元素。
我不知道我在做什么,我已经尝试了几件失败的事情......
我希望能够通过 loading._center();
之类的方式调用它
当函数运行时,它附加加载 div 并使用上面的代码计算绝对定位顶部和左侧。我希望它在窗口调整大小时保持居中,所以我基本上复制了上面的代码并用 $(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);
最佳答案
你可以为第二个参数提供一个函数:
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';
});
这是 documentation .css() 的。
关于javascript - 编写一个 jquery 函数来重用一个公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6714939/