Skip to content

Instantly share code, notes, and snippets.

@STAR-ZERO
Created March 1, 2012 07:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save STAR-ZERO/1948013 to your computer and use it in GitHub Desktop.
Save STAR-ZERO/1948013 to your computer and use it in GitHub Desktop.
要素内の文字の行数を取得する

要素内の文字の行数を取得する

テキトーに書いた。 Chromeでしか確認してない。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').click(function() {
var text = $('#hoge').text();
// 1行の高さ取得
$('#hoge').text('a');
var rowHeight = $('#hoge').height();
var rowCount = 1;
// 一旦空にする
$('#hoge').text('');
for (var i = 0; i < text.length; i++) {
// 一文字取得して追加
var s = text.substring(i, i + 1);
$('#hoge').text($('#hoge').text() + s);
// 現在の高さ取得
height = $('#hoge').height();
if (height != rowHeight) {
// 高さが変わったら行数インクリメント
rowHeight = height;
rowCount++;
}
}
alert(rowCount);
});
});
</script>
</head>
<body>
<p id="hoge" style="word-break:break-all">ああああああああああああああああああああaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbb</p>
<input type="button" value="get row count" id="btn">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment