我找到的唯一解决方案是 ($(this).innerHeight() - $(this).height())/2
但是/2 不是正确的选项,因为用户可以有 padding-top:0px 和 padding-bottom:20px。
有没有办法使填充值更准确?
我在考虑 css('padding-top')
然后解析它,只取 int 部分,但是值可以是“em”而不是“px”
然后为每个值类型制作switch语句?对于 em 一个,对于 px 另一个?
这一切都有点复杂并且占用了更多的代码空间......
最佳答案
jQuery 的主要优势之一是它的可插拔性,因此如果您的需求无法通过库立即得到满足,可以搜索大量的插件。如果没有任何东西可以满足您的需求,那么自己动手真的很容易。
我认为正确的方法是去这里,如果你不能找到一个插件来做你想要的,最后一个:写你自己的。
但是,请确保您清楚自己的插件规范。如果元素没有填充的 css 设置,它应该返回什么?它应该返回此元素的样式还是计算出的样式?无效的 css 会发生什么(例如“padding-top:10 unitsThatDontExist;”或“padding-left:two;”)?
收件人get you started - 这就是在您的代码中使用您自己的插件的样子:
var topPadding = $('#anElement').padding('top');
要使其可用,只需编写如下插件:
$.fn.padding(direction) {
// calculate the values you need, using a switch statement
// or some other clever solution you figure out
// this now contains a wrapped set with the element you apply the
// function on, and direction should be one of the four strings 'top',
// 'right', 'left' or 'bottom'
// That means you could probably do something like (pseudo code):
var intPart = this.css('padding-' + direction).getIntegerPart();
var unit = this.css('padding-' + direction).getUnit();
switch (unit)
{
case 'px':
return intPart;
case 'em':
return ConvertEmToPx(intPart)
default:
// Do whatever you feel good about as default action
// Just make sure you return a value on each code path
}
};
关于jQuery 将 padding-top 计算为 px 中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3278997/