簡體   English   中英

在計算砌體網格中每個div的頂部和左側位置時遇到問題

[英]having issue to calculate each div top and left position in masonry grid

我有創建網格畫廊,其中每個div具有不同的寬度和高度。 我想讓這個畫廊像磚石一樣。

這是我的Jsfiddle演示

這是Java腳本代碼的片段

function posit(){
    $(".sli").css({"position":"relative"});
    var k=0;
    total = $(".sli1").length;

    if(k<total){
        $(".sli1").each(function(){

//          alert(k++);
        //  var selectpos = selectedItems.position();
            $(this).css({"position":"absolute"});
            var c = $(this).position();
            console.log((k) + ':' + c.left);
            var d = $(this).outerWidth();
            $(this).css({"left": (c.left)});
            $(this).css({"top": (c.top)});
        });
    }k++;

};

$(document).ready(function(){
    posit();
});

有人可以幫忙計算每個div的右上角和左上角的位置,以便我可以創建砌體嗎? 請注意:-我不想使用任何插件 提前感謝。

更新,這里是屏幕截圖我想要我的輸出 在此處輸入圖片說明

您可以使用此代碼。 我使用getBoundingClientRect方法獲取頂部,右側,底部,左側的值

我修改了您的代碼。 請檢查是否適合您。

$(".sli1").each(function(){
        var i = $(this);
        i.css({"position":"absolute"});
        var c = i.get(0).getBoundingClientRect();                       
        console.log(c.top,c.left,c.bottom,c.right);
    });

要獲取每個div的位置,請參見以下內容:

if(k<total){
    $(".sli1").each(function(){

    var c = $(this)[0];
    // now you can get the position you want for each of the div as follows:

    console.log("Top: " + c.offsetTop);
    console.log("Left: " + c.offsetLeft);

    //the rest of the code

    });
}k++;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM