detect the widest cell w/ jQuery

前端 未结 5 933
挽巷
挽巷 2021-01-19 21:34

I have a table with different values. First column contains labels. I need to get the width of the widest label. I assume I need some sort of a loop, but then what?

5条回答
  •  Happy的楠姐
    2021-01-19 22:27

    Try this:

    var widest;
    var widestWidth = 0;
    $("#myTable td").each(function(t) {
        if($(this).width() > widestWidth){
            widest = $(this);
            widestWidth = $(this).width();
        }
    });
    //Now widest points to the widest element
    

    Note I tracked the actual width separately from the widest element. An alternate solution without this method would be to initialize widest to a dummy element with width = 0 and just compare $(this).width() with widest.width()

    EDIT: Or, alternately, now that I realize you wanted only the width and not the actual element, you could use this version:

    var widestWidth = 0;
    $("#myTable td").each(function(t) {
         widestWidth = Math.max(widestWidth, $(this).width());
    });
    

提交回复
热议问题