jquery比较img下的高度和h2的高度 [英] jquery compare the height beneath img to h2's height
问题描述
var h2 = $('。block h2');
var divh = $('。block')。height();
while($(h2).outerHeight()> divh){
alert('进入while');
$(h2).text(function(index,text){
return text.replace(/ \W * \s(\S)* $ /,'...') ;
});
}
如下所示:跨浏览器的多行文本溢出,在宽度和高度固定的div内添加省略号? a>
我遇到的问题是我有各种各样的 li
,其中每个包含一个 .block
,其中 h2
标记每个 li
示例:
< li>
< div class =block>
...
< h2> Tittleasfasjgpashgj9ahgpasgnapsighapighapsogna< / h2>
...
< / div>
< / li>
< li>
< div class =block>
....
< h2> 5Tittleasfasjgpashgj9ahgpasgnapsighapighapsogna< / h2>
...
http://i.stack.imgur.com/lI82f.jpg
将 .block
设置为200px,其中 img
设置为 height:90px;
和一个 padding:5px
现在我需要将img下面的高度与 h2
's height。
但它也不起作用,它只是不做if,但
编辑:
所以我只是想知道解决这个问题的最好方法是将高度设置为 h2
标记,并将其内容高度与设置的高度进行比较。
像这样的东西可以正常工作:
$('。block')。each(function(i,el){
var $ h2 = $(el).find('h2');
var divh = $(el).height ();
while($ h2.outerHeight()> divh){
$ h2.text(function(index,text){
return text.replace(/ \W * \s(\S)* $ /,'...');
});
}
});
您应该使用 .block {word-wrap:break-word; }
(或者在这些长长的h2文本中加入一些空格)让它们突破并帮助实现效果。
在原始问题,这只是一个想法,而不是准备在生产中使用的东西。这是相当DOM重,可能不是所有用例的最佳解决方案。
I am trying to adapt this:
var h2=$('.block h2');
var divh=$('.block').height();
while ($(h2).outerHeight()>divh) {
alert('enters while');
$(h2).text(function (index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
as explained here: Cross browsers mult-lines text overflow with ellipsis appended within a width&height fixed div?
The problem I have encountered in my case is that I have various li
where each one contains a .block
which has a h2
tag per li
Example:
<li>
<div class="block">
....
<h2>Tittleasfasjgpashgj9ahgpasgnapsighapighapsogna</h2>
...
</div>
</li>
<li>
<div class="block">
....
<h2>5Tittleasfasjgpashgj9ahgpasgnapsighapighapsogna</h2>
...
http://i.stack.imgur.com/lI82f.jpg
Having .block
set with 200px, inside having img
set to height: 90px;
and a padding: 5px
now I need to take the height left beneath img and compare to h2
's height.
But it doesn't work either, it just doesn't do the if, but divh
contains data (200, the 200px set in css).
Edit:
So I just figure out that the best way to fix this is to set a height to h2
tag and than compare its content height with the set one.
Something like this would work fine:
$('.block').each(function (i, el) {
var $h2 = $(el).find('h2');
var divh = $(el).height();
while ($h2.outerHeight() > divh) {
$h2.text(function (index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
});
You should use .block { word-wrap: break-word; }
(or put some spaces into those long h2 texts) to let them break and help the effect happen.
As I also stated in the original question, this is just an idea, not something ready to be used in production. It is quite DOM-heavy and may not be the best solution for all use cases.
这篇关于jquery比较img下的高度和h2的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!