对每个元素应用不同的 CSS?
Apply different CSS to each element?
我正在尝试遍历具有特定 class 的父元素 ul
的 li
元素,并根据元素的高度为每个元素分配可变边距循环中的前一个元素:
$(function() {
var staticOffset = 66;
var previousHeight = null; // initialization
$(".timeline-tidy li").each(function() {
if (previousHeight) { // exclude the first element
var heightOffset = previousHeight - staticOffset;
this.css('margin-top', heightOffset * -1); // negative margin
}
previousHeight = this.height();
});
});
虽然我显然做错了什么。你能帮帮我吗?
您没有在函数中正确引用 this
。您需要用 $()
将其包装成一个 jQuery 对象,既要设置 css 又要获取高度...
$(function() {
var staticOffset = 66;
var previousHeight = null; // initialization
$(".timeline-tidy li").each(function() {
if (previousHeight) { // exclude the first element
var heightOffset = previousHeight - staticOffset;
$(this).css('margin-top', heightOffset * -1); // negative margin
}
previousHeight = $(this).height();
});
});
但是,由于您不止一次这样做,我建议创建一个本地引用,就像这样...
$(function() {
var staticOffset = 66;
var previousHeight = null; // initialization
$(".timeline-tidy li").each(function() {
var $this = $(this);
if (previousHeight) { // exclude the first element
var heightOffset = previousHeight - staticOffset;
$this.css('margin-top', heightOffset * -1); // negative margin
}
previousHeight = $this.height();
});
});
我正在尝试遍历具有特定 class 的父元素 ul
的 li
元素,并根据元素的高度为每个元素分配可变边距循环中的前一个元素:
$(function() {
var staticOffset = 66;
var previousHeight = null; // initialization
$(".timeline-tidy li").each(function() {
if (previousHeight) { // exclude the first element
var heightOffset = previousHeight - staticOffset;
this.css('margin-top', heightOffset * -1); // negative margin
}
previousHeight = this.height();
});
});
虽然我显然做错了什么。你能帮帮我吗?
您没有在函数中正确引用 this
。您需要用 $()
将其包装成一个 jQuery 对象,既要设置 css 又要获取高度...
$(function() {
var staticOffset = 66;
var previousHeight = null; // initialization
$(".timeline-tidy li").each(function() {
if (previousHeight) { // exclude the first element
var heightOffset = previousHeight - staticOffset;
$(this).css('margin-top', heightOffset * -1); // negative margin
}
previousHeight = $(this).height();
});
});
但是,由于您不止一次这样做,我建议创建一个本地引用,就像这样...
$(function() {
var staticOffset = 66;
var previousHeight = null; // initialization
$(".timeline-tidy li").each(function() {
var $this = $(this);
if (previousHeight) { // exclude the first element
var heightOffset = previousHeight - staticOffset;
$this.css('margin-top', heightOffset * -1); // negative margin
}
previousHeight = $this.height();
});
});