Javascript 如何编写一个变量来调用Jquery页面上所有元素的所有边距?
标题几乎说明了一切,我不知道这是基本的还是高级的,但我需要一个变量,它将是页面上每个有页边距的元素的所有上下页边距的总和。我不需要左边或右边的。这很容易做到吗?试试这个:Javascript 如何编写一个变量来调用Jquery页面上所有元素的所有边距?,javascript,jquery,css,Javascript,Jquery,Css,标题几乎说明了一切,我不知道这是基本的还是高级的,但我需要一个变量,它将是页面上每个有页边距的元素的所有上下页边距的总和。我不需要左边或右边的。这很容易做到吗?试试这个: function sumMargins() { var total = 0; $("*").each(function() { var top = parseInt($(this).css("marginTop")); var bottom = parseInt($(this).
function sumMargins() {
var total = 0;
$("*").each(function() {
var top = parseInt($(this).css("marginTop"));
var bottom = parseInt($(this).css("marginBottom"));
total += (top + bottom);
});
return total;
}
请看这是一把小提琴: 我添加了一个.container div来限制*选择器,否则它还将包括html和body标记,这两个标记的边距不一致(我有8个像素)
上面的解决方案速度更快,但更可靠。使用此选项时,请注意,这会将DOM中的所有边距相加,包括
body
元素的边距。如果需要,可以将$(“*”)
选择器更改为$(“body”).children()
或其他内容。
var x = 0;
$('*').each(function() {
x += parseInt($(this).css('margin-top'));
x += parseInt($(this).css('margin-bottom'));
});
alert(x);
function allMargins() {
var total = 0;
$('.container *').each(function(i) {
var currentTop = parseInt($(this).css('margin-top'));
var currentBottom = parseInt($(this).css('margin-bottom'));
total = total + currentTop + currentBottom;
});
return total;
}
alert('The total of the margins is: ' + allMargins());