【发布时间】:2014-11-15 10:15:19
【问题描述】:
我在 Jquery 中创建了一个函数,它应该使元素垂直居中(我无法使用 css 做到这一点,累了,只是以编程方式完成了 ^^)。现在的问题是我最初使用 .each 创建它,然后,由于它已经是创建者,我尝试使用选择器 ($('something').center) 调用它,但由于某种原因它的行为有所不同。
使用选择器,它似乎对每个元素都做了同样的事情。它对第一个元素执行此操作,然后将所有值应用于其余元素。因此,例如,我的函数获取元素高度并对其进行一些操作,但选择器仅获取第一个,然后将其参数应用于每个人..
我会继续使用每一个,因为它现在效果最好,但我仍然不明白他们为什么这样做..
居中功能:
$.fn.center = function (){
/*If this is the highest element, or
if this element has full use of the width,
then there's no need to align it.
*/
if(this.height() == this.parent().height() ||
this.width() == this.parent().width())
{
this.css({
position : "relative",
top : 0
});
}
else //Should be aligned.
{
this.css({
position : "relative",
top : (this.parent().height()/2)-(this.height()/2)
});
}
return this; //Used for chaining.
};
这是我的意思的一个例子^^ http://jsfiddle.net/lrojas94/pmbttrt2/1/
【问题讨论】:
标签: javascript jquery html css web