尝试这个:
<div class="wrap">
<span id='first'>Lorem elit</span><span id='second'> Vivamus amet, consectetur</span>
</div>
<script>
/* Check if span is broken into two lines or not */
var firstBefore = document.createElement('span'),
firstAfter = document.createElement('span'),
secondBefore = document.createElement('span'),
secondAfter = document.createElement('span');
first.insertBefore(firstBefore, first.childNodes[0]);
first.appendChild(firstAfter);
second.insertBefore(secondBefore, second.childNodes[0]);
second.appendChild(secondAfter);
var firstBroken = (firstBefore.offsetTop === firstAfter.offsetTop) ? false : true,
secondBroken = (secondBefore.offsetTop === secondAfter.offsetTop) ? false : true;
/* Since the spans' baselines seem to be aligned by default, lets compared that instead */
first.offsetBottom = (first.offsetTop + first.offsetHeight);
second.offsetBottom = (second.offsetTop + second.offsetHeight);
/* Main logic */
if (first.offsetBottom === second.offsetBottom) {
if (!firstBroken && !secondBroken) {
alert('Begins and ends on the same line');
} else if (firstBroken) {
alert('Begins on different lines, but end on the same line');
}
} else {
if (firstBroken) {
alert('Begins and ends on different lines');
} else {
alert('Begins on the same line, but ends on different lines');
}
}
</script>
或者在这里玩:http: //jsfiddle.net/RYEnY/1/
确保使用不同长度的文本运行。
它的工作原理是首先在要检测<span>
的每个目标的开头和结尾插入一个隐藏。<span>
然后,代码通过比较隐藏的 span来检查目标<span>
是否被分成两行。offsetTop
然后,它获取每个目标跨度的基线偏移量,并从逻辑上推断跨度是否在同一行开始/结束。