文章のデザインを組んでいる時に、高さを抑えたい場合がたまにあります。
スクロールをつけることもありですが、他に以下のように隠れた情報は、ボタンを押すと出てくるという表現はいかがでしょうか。
テキストが三行以下の場合何も起こりません。
文字の量高さより少ない場合はそのまま表示されます。
<div> <div class="demo_txt"> 文字の量高さより少ない場合はそのまま表示されます。 </div> </div>
テキストが三行を超える場合、そのテキストの枠の下に「続きを見る」ボタンを表示します。
文字の量が多く、規定の高さを超える場合、テキストのある枠の下にもっと見るボタンを表示します。
パソコンで読む場合は、ある程度文字の量があっても、耐えられますが、スマホなどで見ている場合は、
読みたくない文字は飛ばして見たい場合があるため、こういった対応となります。
<div> <div class="demo_txt" > 文字の量が多く、規定の高さを超える場合、テキストのある枠の下にもっと見るボタンを表示します。 パソコンで読む場合は、ある程度文字の量があっても、耐えられますが、スマホなどで見ている場合は、 読みたくない文字は飛ばして見たい場合があるため、こういった対応となります。 </div> </div>
上記のJavaScriptは以下になります。
$(function(){ //テキストをチェック var i = 0; $('.demo_txt').each(function() { sHeight = $('.demo_txt').get(i).scrollHeight;// 隠れているテキストの高さ oHeight = $('.demo_txt').get(i).offsetHeight;// 表示されているテキストの高さ hiddenDiff = sHeight - oHeight; if(hiddenDiff > 0){ $(this).parent().append('<div class="demo_more" >続きを見る</div>') } i++; }); // more $(".demo_more").click(function() { //get data txt_height = parseInt($(this).parent().find(".demo_txt").css('height'),10); sHeight = $(this).parent().find(".demo_txt").get(0).scrollHeight; oHeight = $(this).parent().find(".demo_txt").get(0).offsetHeight; hiddenDiff = sHeight - oHeight; new_txt_height = txt_height + hiddenDiff; $(this).parent().find(".demo_txt").animate({ height: new_txt_height}, 1000 ); $(this).slideUp(); }); });
参考にCSSは以下になります。
.demo_txt { height:60px; line-height:20px; font-size:14px; background-color:#000; color:#FFF; width: 250px; margin: 0 auto 10px; overflow-y:hidden; padding:10px; } .demo_more{ cursor: pointer; background-color: #DCC; color: #444; border-radius: 10px; height:20px; line-height: 20px; text-align: center; width: 250px; margin: 0 auto 10px; }