1. 程式人生 > >jsp選項過長自動換行

jsp選項過長自動換行

自動換行前是這樣的

 

從原始碼發現“打發的所發生的7”所在span跨行了,寬度為整行的寬度,不再是自身的實際寬度(一列時所佔的寬度)

我的思路是要把這個換行元素前加上<br/>,使得該元素換行

$(".question").each(function(index,item){
    dynamicWidth(index,item);
});
function dynamicWidth(index,item){
    if($(item).children(".options").html()){//單選或多選
        var totalWidth=0;
        $(item).children(
".options").each(function(index2,item2){ totalWidth+=$(item2).width(); if(totalWidth>$(".content").width()){ totalWidth=$(item2).width(); $(item2).prop('outerHTML',"<br/>"+$(item2).prop('outerHTML')); } }); } }

但效果並不令人滿意

在“打發的所發生的7”所在span元素前後各加了一個換行。為什麼會這樣呢?因為元素換行寬度固定了,

totalWidth=$(item2).width();

實際上得出的仍是換行寬度,必須重新遍歷父元素所含子元素才能獲取$(item2).width();的真實寬度。一旦出現換行就結束本次迴圈肯定是不可以的,因為不能保障下面的元素不會有換行需求。所以遞迴處理該元素是唯一正確思路。於是最終的解決辦法:

$(".question").each(function(index,item){
        dynamicWidth(index,item);
});

function dynamicWidth(index,item){ var f=true; var item2=null; if($(item).children(".options").html()){//單選或多選 var totalWidth=0; $(item).children(".options").each(function(index2,item2){ totalWidth+=$(item2).width(); if(totalWidth>$(".content").width()){ totalWidth=$(item2).width(); $(item2).prop('outerHTML',"<br/>"+$(item2).prop('outerHTML')); //獲取當前迴圈的元素(已處理過),方便遞迴呼叫該元素。若從頭開始迴圈或迴圈處理前的元素,則會死迴圈。因為跨行元素寬度固定,不會因為換行自動減小寬度 item2=$(".question:eq("+index+")"); f=false; return f; } }); if(!f){ dynamicWidth(index,item2); } } }

 結果也很令人滿意: