JS動態(tài)更改div高度實現(xiàn)代碼例子
更新時間:2023年11月11日 08:29:58 作者:洋哥登陸
在Web開發(fā)中通過使用JavaScript可以動態(tài)地修改HTML元素的屬性和樣式,下面這篇文章主要給大家介紹了關(guān)于JS動態(tài)更改div高度實現(xiàn)的相關(guān)資料,文中給出了詳細的代碼示例,需要的朋友可以參考下
前言
通過JS動態(tài)更改div高度。高度大于限定值內(nèi)容進行折疊,顯示view more。點擊后顯示全部內(nèi)容。
js代碼
<html> <body onload="queryHeight()"> <!-- div容器 --> <div class="container"> <!-- 文本內(nèi)容 高度可能為1000以上 --> </div> <div id="readMore" class="readMore"> <div class="readBackground"></div> <div class="readText" onclick="show()"> Read more ∨</div> </div> <script> var contentHeight = 0 function queryHeight() { const content = document.getElementsByClassName('container')[0] // 要獲得真實高度,需用 onload 來執(zhí)行方法 contentHeight = content.offsetHeight if(content.offsetHeight > 800){ content.style.height = 800 content.style.overflow = 'hidden' } } function show() { const content = document.getElementsByClassName('container')[0] content.style.height = contentHeight content.style.overflow = '' const readMore = document.getElementById('readMore') readMore.style.display = 'none' } </script> </body> </html> <style> body{ margin: 0px; width: 100%; height: 100%; background-color: #EFEFEF; } .container{ width: 100%; height: 1500px; background-color: #FFFFFF; } .td-content{ height: auto; } /* read-more */ .readMore{ position: absolute; width: 100%; height: 60px; text-align: center; font-size: 14px; font-family: 'Roboto-Regular, Roboto'; font-weight: 600; color: #000000; line-height: 40px; } .readBackground{ width: 100%; height: 20px; background: linear-gradient(180deg, rgba(255,255,255,0) 0%, #FFFFFF 100%); } .readText{ background-color: #FFFFFF; } </style>
效果
點擊前
點擊后
總結(jié)
到此這篇關(guān)于JS動態(tài)更改div高度實現(xiàn)的文章就介紹到這了,更多相關(guān)JS動態(tài)更改div高度內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
輕松實現(xiàn)javascript數(shù)據(jù)雙向綁定
這篇文章教大家輕松實現(xiàn)javascript數(shù)據(jù)雙向綁定,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2015-11-11JavaScript中合并Object的三種基本方法小結(jié)
在開發(fā)過程中,我們經(jīng)常會遇到合并對象的需求,今天我們就來了解一下合并對象的幾種基本方法,文中通過代碼示例介紹的非常詳細,感興趣的小伙伴跟著小編一起來看看吧2023-08-08基于JavaScript代碼實現(xiàn)隨機漂浮圖片廣告
在網(wǎng)上有很多這樣的代碼,不過未必符合W3C標準,因為在頭部加上<!DOCTYPE html>類似標簽之后,漂浮效果就會失效,下面分享一個符合標準的漂浮代碼,使需要的朋友免去大量改造代碼的繁瑣2016-01-01