-1

我想在一个变量中计算或添加所有框宽度的宽度。我应该使用循环或类似的东西。请建议

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>

    <style>
        .container { 
            width: 610px; 
            overflow: hidden; 
            position: relative; 
            height: 300px;
        }
        .con { position:absolute; left:0; width:2000px}
        .box { float:left; width:200px; 
               height:200px; margin-right:5px; 
               background:#F00; margin-top:5px;}
    </style>
    <script type="text/javascript" src="jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(function (){
            $('a').click(function (){
                alert($('.box').width())
            })
        })
    </script>
</head>

<body>
    <div class="container">
        <div class="con">
            <div class="box">df</div>
            <div class="box">adfa</div>
            <div class="box">asdf</div>
        </div>
    </div>
    <a href="#">click</a>
</body>
4

3 回答 3

4

This single expression using reduce will return the total width:

var total = $('.box').get().reduce(function(prev, current, index, array) {
    return prev + current.offsetWidth;
}, 0);

Use $(current).width() or related variants if the DOM .offsetWidth isn't the metric you want.

于 2012-07-17T13:08:17.267 回答
1

您可以使用循环遍历每个.box元素.each()并将宽度添加到变量:

$('a').click(function(ev){
    var totalWidth = 0;
    $('.box').each(function(i, el){
        totalWidth += $(this).width();
    }
    alert(totalWidth);
});
于 2012-07-17T13:06:45.290 回答
0

对于循环,您可以将 each() 与 jQuery 一起使用:http: //api.jquery.com/jQuery.each/

类似的东西:

$('a').click(function (){
    $('div').each(function (){
        //TO DO FOR EACH DIV ON YOUR PAGE
    });
});
于 2012-07-17T13:03:55.783 回答