jsp选项过长自动换行

时间:2024-04-30 17:18:44

自动换行前是这样的

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'));
}
});
}
}

但效果并不令人满意

jsp选项过长自动换行

在“打发的所发生的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);
}
}
}

结果也很令人满意:

jsp选项过长自动换行