-1

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

を使用するこの単一の式reduceは、合計幅を返します。

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

DOMが必要なメトリックでない$(current).width()場合は、または関連するバリアントを使用します。.offsetWidth

于 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

ループの場合、jQueryでeach()を使用できます: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 に答える