LoginSignup
10
7

More than 1 year has passed since last update.

【JS】指定行数を越えたら全文が表示されるボタンをつける

Last updated at Posted at 2020-04-20

JSで指定した行数を越えたら、全文を表示するボタンを出す処理を作っていきたいと思います。

指定した行の高さにするには

例えば、5行分の高さにしたくて height: 5rem; にしても、5行にはうまいことなりません。行の高さはfont-sizeline-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ボタンは表示されません。

参考
テキストエリアの高さを行数で指定する本当に正しい方法

10
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7