JSで指定した行数を越えたら、全文を表示するボタンを出す処理を作っていきたいと思います。
指定した行の高さにするには
例えば、5行分の高さにしたくて height: 5rem;
にしても、5行にはうまいことなりません。行の高さは**font-size
とline-height
から計算される**ためです。
対処法
そこで今回はCSSのline-height
の値を取得し、font-size
と掛け合わせ実際の行の高さを求めます。
注意点としては、JSで取得できるline-height
はピクセルで返ってくるので注意が必要です。
<div class="wrapper">
<p class="text">
1行目<br>
2行目<br>
3行目<br>
4行目<br>
5行目<br>
6行目<br>
</p>
<div class="more-button">More</div>
</div>
style.scss
.wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.text {
font-size: 18px;
line-height: 1.8;
overflow: hidden;
// 全行表示
&.is-open {
height: 100% !important;
}
}
.more-button {
background-color: #666;
width: 100px;
padding: 15px 0;
border-radius: 4px;
line-height: 16px;
text-align: center;
font-size: 16px;
color: #fff;
}
script.js
const textContents = document.querySelector('.text');
const moreButton = document.querySelector('.more-button');
// テキスト要素の高さを取得
const textHeight = textContents.clientHeight;
// テキスト要素のline-heightを取得
let lineHeight = getComputedStyle(textContents).getPropertyValue('line-height');
// [32.4px]のようなピクセル値が返ってくるので、数字だけにする
lineHeight = lineHeight.replace(/[^-\d\.]/g, '');
// メニューが6行以上だったら高さを5行にする
if(textHeight > lineHeight * 5) {
textContents.style.height = `${lineHeight * 5}px`;
} else {
// メニューが5行以下ならMoreボタン非表示
moreButton.style.display = 'none';
}
// Moreボタンを押したら、テキスト要素のis-openクラスを切り替え
moreButton.addEventListener('click', () => {
textContents.classList.toggle('is-open');
});
Moreボタンを押すと全行が表示されます。また5行以下だとMoreボタンは表示されません。