我认为这是一个相当简单的问题,但......
var outerHeight = $('.profile').outerHeight();
$("#total-height").text(outerHeight + 'px');
Run Code Online (Sandbox Code Playgroud)
现在var outerHeight给了我仅包含类的第一个元素的outerHeight .profile.
如何获得所有元素的outerHeights 与类的总和.profile?
Fla*_*ash 28
遍历每个匹配元素并加上外部高度:
var outerHeight = 0;
$('.profile').each(function() {
outerHeight += $(this).outerHeight();
});
$("#total-height").text(outerHeight + 'px');
Run Code Online (Sandbox Code Playgroud)
Jua*_*des 13
这是直截了当的解决方案.只需遍历总结outerHeight()s 的jQuery对象的元素.
var total = 0;
$('.profile').each(function(){
total += $(this).outerHeight();
});
// total is good here
Run Code Online (Sandbox Code Playgroud)
重要的是,所有jQuery getter只返回jQuery集中第一个元素的值,但您可以自己添加它们.
这是一个环形交叉但很酷的做法http://jsfiddle.net/mendesjuan/bKtAn/6/
// You can use a jQuery object as the `this` param in `Array.prototype` functions
var totalHeight = Array.prototype.reduce.call($('span'), function(a,b){
// The first param is either the default value (passed into reduce)
// or the result of the last call of this reducing function
return a + $(b).outerHeight();
}, 0);
Run Code Online (Sandbox Code Playgroud)
哪个可以概括为http://jsfiddle.net/mendesjuan/bKtAn/7/
function addjQValues($jq, getter) {
return Array.prototype.reduce.call( $jq, function (a, b) {
return a+ getter.call($(b));
}, 0);
}
addjQValues($('span'), $.fn.height)
Run Code Online (Sandbox Code Playgroud)
并制作了一个插件,如:http://jsfiddle.net/mendesjuan/bKtAn/9/
(function( $ ) {
$.fn.addUp = function(getter) {
return Array.prototype.reduce.call(this, function(a,b){
return a + getter.call($(b));
}, 0);
}
})(jQuery);
$('span').addUp($.fn.height);
$('span').addUp($.fn.width);
$('span').addUp($.fn.text);
Run Code Online (Sandbox Code Playgroud)
我觉得我有点过火,对不起,我很兴奋,但这些代码片段教你很多关于JS甚至一些jQuery的知识
$("selector")已经是一个集合。 直接访问.outerHeight()或任何其他方法,例如.height()
var total = 0;
$("div").outerHeight(function(i, v){
total += v;
});
alert( total ); // Just to test
Run Code Online (Sandbox Code Playgroud)
var total = 0;
$("div").outerHeight(function(i, v){
total += v;
});
alert( total ); // Just to test
Run Code Online (Sandbox Code Playgroud)
var total = 0;
$("div").outerHeight(function(i, v){ total += v; });
alert( total );Run Code Online (Sandbox Code Playgroud)
div{background:#eee; margin:3px;}Run Code Online (Sandbox Code Playgroud)