javascript 長い文章を一部表示に変更する
- 作成日 2021.06.09
- 更新日 2022.09.01
- javascript
- javascript

javascriptで、長い文章を一部表示に変更するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.101
一部表示に変更
一部表示に変更にするには、文字列の一部を返してくれる「substr」を使用することで可能です。
<div>
<p id="hoge">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make
a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting,
remaining essentially unchanged.
</p>
<input id="btn" type="button" value="ボタン" />
</div>
<script>
'use strict';
document.getElementById('btn').onclick = function () {
const elm = document.getElementById('hoge');
// 表示する文字数は100に指定
elm.innerHTML.length <= 100 ? elm.innerHTML: (elm.innerHTML = elm.innerHTML.substr(0, 100)+"...");
}
</script>
実行結果を確認すると、文章が一部表示に変更されていることが確認できます。

また、以下のコードを、
document.getElementById('btn').onclick = function () {
const elm = document.getElementById('hoge');
elm.innerHTML.length <= 100 ? elm.innerHTML: (elm.innerHTML = elm.innerHTML.substr(0, 100)+"...");
}
アロー関数を使用して、簡潔に記述することもできます。
btn.onclick = () =>{
hoge.innerHTML.length <= 100 ? hoge.innerHTML: (hoge.innerHTML = hoge.innerHTML.substr(0, 100)+"...");
}
サンプルコード
以下は、
「実行」ボタンをクリックして、テキストノードを範囲を指定して選択状態にするサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
const hoge = () => {
foo.innerHTML.length <= 100 ? foo.innerHTML: (foo.innerHTML = foo.innerHTML.substr(0, 100)+"...");
}
window.onload = () => {
btn.onclick = () => { hoge() };
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<div id="foo">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make
a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting,
remaining essentially unchanged.
</div>
<button id="btn"
class="mb-2 md:mb-0 bg-indigo-400 px-5 py-2 text-sm shadow-sm font-medium tracking-wider text-white rounded-full hover:shadow-lg hover:bg-indigo-500">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、指定した範囲のテキストノードが選択されていることが確認できます。

-
前の記事
C# テキストファイルの内容を全て取得する 2021.06.09
-
次の記事
go言語 ファイルやフォルダの存在確認を行う 2021.06.09
コメントを書く