我在 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/
最佳答案
对于简单的事情,比如以相同的方式为具有相同类的所有元素更改 CSS,您可以直接调用它而无需使用 .each()
。例如:
$('.elem').css('color', '#fff');
但是如果每个 div 都需要以单独的值结尾,您应该使用 .each()
。例如(抱歉有点奇怪):
var border = 1;
$('.elem').each(function() {
$(this).css('border', border + 'px solid #000');
border += 1;
});
基本上,如果您不使用 .each()
,它会检查您要更改的内容(仅一次!)并将其应用于该类的所有元素。如果您确实使用了 .each()
,它将针对每个元素单独执行。
关于javascript - Jquery each 和 Selector 的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26941627/