前言
在開發的時候會遇到這種情況,只顯示兩行,如果超過兩行,則顯示一個“顯示更多”的按鈕,點擊按鈕來顯示剩餘行的內容。有個jQuery 的插件loadingDots專門實現了這個功能。不過今天這裡我們要用原生的Javascript來實現,要實現這個需求,最關鍵的是要確定這個容器內文本的行數,得到行數後,修改元素高度,並確定是否顯示加載按鈕。
window.getComputedStyle()
要使用原生JavaScript 代碼獲取一個元素的各個style 屬性,使用window.getComputedStyle()是必然的。它可以返回一個HTML 元素在瀏覽器中真正顯示時的各個樣式――當然,有些樣式會被瀏覽器給屏蔽,比如,你要獲取一個鏈接的顏色,並準備通過顏色來判斷用戶是否訪問過某個地址,那肯定是不行的。
該方法返回的,是一個樣式鍵值對,是CSSStyleDeclaration的實例。各屬性索引名沒有- ,且採用駝峰命名法。比如lineHeight 。
行數= 整體高度/ 行高
整體高度通過height 可以獲取。行高可以通過lineHeight獲取,將其結果再取整即可得到行數。
但有個問題,如果沒有針對一個元素設置line-height值,則其默認值為normal ,這個值在桌面瀏覽器中通常是1.2 ,但還與字體有關。因此,最好是對需要計算行數的元素設置一下line-height值。
一個簡單的實現如下:
function countLines(ele) { var styles = window.getComputedStyle(ele, null); var lh = parseInt(styles.lineHeight, 10); var h = parseInt(styles.height, 10); var lc = Math.round(h / lh); console.log('line count:', lc, 'line-height:', lh, 'height:', h); return lc;}完整代碼示例
<!DOCTYPE html><html><head> <title>Line Count</title> <style type="text/css"> p { line-height: 1.3em; } </style><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head><body><p id="target">She just made having a baby look lovely. Everything is white and she always has a fresh blueberry pie that's steaming and scones and clotted cream and she's reading The Old Man and the Sea and her little boy is rolly with bonnets. It's amazing, and I thought this is lovely. My kid is like playing with like explosive devices. I don't know where she's found them, like sticking them in our dog's ear. She already knows how to dry wall cause she puts holes in the wall.<br />“今天的中國人一如當年的德國人,沉迷於'崛起'幻覺,習慣於聽信他人的吹捧,還想當然地認為只要中國繼續保持經濟增長,不僅未來的經濟總量超越'世界老大'美國可以期待,中國實現全面復興也將是囊中之物。”上海外國語大學國際關係與公共事務學院教授程亞文在其新著《大國戰略力》中尖銳地指出中國現下有不少人陷入了“盛世”幻覺,並沒有意識到在經濟總量的背後,中國其實還是一個極為落後的國家。世界上還沒有一個大國是在風平浪靜中興起的,中國的新一輪文明復興也將充滿風險和曲折。防止國家崩潰、解體或衰敗應該成為中國國家戰略的重中之重。染上“軟乎乎的幸福主義”只會讓一個國家變得脆弱。 </p><p>行數:<span id="shower"></span></p>改變窗口大小,自動計算<button onclick="countLines()">立刻計算</button><script type="text/javascript">var target = document.getElementById('target');var shower = document.getElementById('shower');function countLines(ele) { var styles = window.getComputedStyle(ele, null); var lh = parseInt(styles.lineHeight, 10); var h = parseInt(styles.height, 10); var lc = Math.round(h / lh); console.log('line count:', lc, 'line-height:', lh, 'height:', h); return lc;}function change() { shower.innerHTML = countLines(target);}window.onresize = change;change();</script></body></html>[/html]總結
以上就是本文的全部內容,希望本文的內容對大家使用Javascript能有所幫助。如果有疑問可以留言討論。