如何使用jQuery检查行数 [英] How to check for # of lines using jQuery

查看:74
本文介绍了如何使用jQuery检查行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:一个宽度为30px的div,其单词为"this is text".可以说,由于宽度很窄,因此它在页面上的呈现方式如下:

Example: a div with width of 30px with the words "this is text". Let's say that, since the width is narrow, it renders on the page like this:



文字

this
is
text

(3行). jQuery中是否有一种方法可以告诉渲染到页面需要多少行?例如,类似$("#container").lineCount().

(3 lines). Is there a way in jQuery to tell how many lines it takes to render to the page? For example, something like, $("#container").lineCount().

经营宗旨:如果我的内容超过一定的行数,我想对其进行处理,以使滚动条不会出现,但是我的高度也固定,因此我不想弄乱CSS道具

Business purpose: if my content exceeds a certain number of lines, I want to manipulate it so that a scroll bar does not appear, but I also have a fixed height, so I don't want to mess with overflow css prop.

谢谢!

推荐答案

这很棘手,但是即使没有指定的行高或其他样式也可以做到.它确实涉及许多运动部件.

This is tricky but can be done, even if there is no specified line-height or other style. It does involve a bunch of moving parts.

首先,构建一个牺牲"容器<div>.用已知数量的文本行填充文本,每行一个字符,然后将其放置在屏幕之外:

First, build a "sacrificial" container <div>. Fill it with a known number of lines of text, one character each, and position it far off-screen:

// calculate height per line
$calcdiv = $('<div/>').css({
  width: '50px',
  position: 'absolute', // don't affect layout
  left: '-2000px' // position far off=screen
}).html('A<br />B<br />C<br />D<br />E'); // add five lines

$('body').append( $calcdiv ); // make the browser render it

var lineHeight = $calcdiv.height()/5; // average height per line

现在,我们知道该浏览器渲染的线条的大约高度(以像素为单位).我们将注意力转向要测量的盒子:

Now we know the approximate height of a line, in pixels, as rendered by this browser. We turn our attention to the box to be measured:

$origDiv = $('div#div_to_measure');
$measureDiv = $origDiv.clone(); // clone it
$measureDiv.css({
  position: 'absolute',
  left: '-1000px', // position far off-screen
  height: 'auto' // let it grow to its natural full height
});
$('body').append( $measurediv ); // add it to the DOM, browser will render it

...现在,如果允许其达到浏览器呈现的自然尺寸,我们现在知道框中的大概行数:

...and now we know the approximate number of lines in the box if allowed to attain its natural dimensions as rendered by the browser:

var numLines = $measureDiv.height() / lineHeight;

我们必须clone(),因为要测量的原始框的高度可能受当前页面样式和布局的限制.

We have to clone() because the original box to be measured may have its height restricted by the current page styles and layout.

现在进行一些清理:

$calcdiv.remove();
$measureDiv.remove();

这里是一个示例: http://jsfiddle.net/redler/FuWue/

这篇关于如何使用jQuery检查行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆