一个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
}
};
parseInt函数(this.css( “填充 - ” +方向))将其转换为整数。 – Psytronic 2010-07-19 07:19:45
不,它不。并且“这个”应该被包装顺便说一句。 – Somebody 2010-07-19 07:35:31
@Psytronic,好 - 很高兴知道! =)然而,我故意没有在这个插件中写出所有的代码,以便让OP不得不实际地对它进行一些修改,而不仅仅是复制粘贴。这是一个更好的学习方式;) – 2010-07-19 07:36:27