Nov*_*ova 5 html javascript jquery string-length
我有一个无序列表,其中包含3个列表项(在我的示例中表示为3个绿色框).每个方框都有一个图像和3个div(标题,位置,价格).我只关心每个盒子的标题div.
如果标题足够长,以便产生2行,我希望顶行总是短于底线.我在这里看到的演示站点显示了错误设置的方框1和2,方框#3显示了正确的设置.
我遇到了麻烦......这可能需要js来确定行长度,然后将底线设置得更长.屏幕分辨率可能会起作用,但我不能在不同的屏幕尺寸上使线条一致吗?
这是列表项之一,我对div"titlebox"感兴趣:
<li class="list__item">
<figure class="list__item__inner">
<p class="vignette" style="background-image:url(http://www.ht-real-estate.com/template/ht2014/images/landscape/05.jpg)"></p>
<div class="titlebox">This line is longer than this line</div>
<div class="locationbox">Location</div>
<div class="pricebox">Price</div>
</li>
Run Code Online (Sandbox Code Playgroud)
任何帮助都很棒,谢谢!!
附上截图: 
这是一个在大多数情况下可能适合您的 JS 解决方案(我说大多数情况是因为文本字符可以具有不同的宽度)。它基本上将您的句子分成两行,并带有动态插入的<br>标签。代码中的注释:
$(".titlebox").each(function(){
var len = $(this).text().length,
words = $(this).text().split(" "),
line1 = [],
line2 = [],
html = "";
// iterate through each word in the title
$.each(words, function(i,word){
// if line 1's current length plus the length of this word
// is less than half the total characters, add word to line 1
// else add to line 2
// (check index of word to maintain order)
if((line1.join(" ")+" "+word).length < (len/2) && (i == line1.length)){
line1.push(word);
} else {
line2.push(word);
}
});
// concatenate the results with a '<br>' separating the lines
html = line1.join(" ")+"<br>"+line2.join(" ");
// replace the .titlebox content with this new html string
$(this).html(html);
});
Run Code Online (Sandbox Code Playgroud)