2013-07-30 16 views

回答

0

試試這個:

function sumMargins() { 
    var total = 0; 
    $("*").each(function() { 
     var top = parseInt($(this).css("marginTop")); 
     var bottom = parseInt($(this).css("marginBottom")); 
     total += (top + bottom); 
    }); 
    return total; 
} 

this fiddle.

+0

完美,謝謝。 – Muskogeee

+0

使用這個時,請注意,這會將DOM **中的所有邊距相加,包括'body'元素的所有邊距,等等。您可以將'$(「*」)'選擇器更改爲'$(「body 「).children()'或其他你需要的東西。 – theftprevention

0
var x = 0; 

$('*').each(function() { 
    x += parseInt($(this).css('margin-top')); 
    x += parseInt($(this).css('margin-bottom')); 
}); 

alert(x); 
0

這裏是工作提琴:

http://jsfiddle.net/jonigiuro/qQ6sB/

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()); 

我添加了一個.container DIV限制*選擇器,否則它也會包含html和body標籤,這些標籤對邊距不一致(我有8個像素)。上述

的解決方案更快,但這是更加牢固。

相關問題