JS实现显示部分文字点击显示全部的示例
JS如何实现显示部分文字,点击又显示全部的呢?
代码如下:
<div id="box"> <h2>建站学习网</h2> <p>建站学习网建站学习网建站学习网建站学习网建站学习网</p> <p>建站学习网建站学习网建站学习网建站学习网建站学习网建站学习网建站学习网建站学习网建站学习网建站学习网建站学习网建站学习</p> </div> <script> function show(){ var pp = document.getElementsByTagName("p"); for (var i = 0; i < pp.length; i++) { var text = pp[i].innerHTML; //alert(text); var newBox = document.createElement("div"); var newBox2 = document.createElement("div"); var btn = document.createElement("a"); newBox.innerHTML = text.substring(0,10); newBox2.innerHTML = text; newBox2.style.display="none"; btn.innerHTML = text.length > 10 ? "...显示全部" : ""; btn.href = "###"; btn.onclick = function(e){ if (e.target.innerHTML == "...显示全部"){ e.target.innerHTML = "收起"; e.target.previousSibling.previousSibling.innerHTML = e.target.previousSibling.innerHTML; }else{ e.target.innerHTML = "...显示全部"; e.target.previousSibling.previousSibling.innerHTML = e.target.previousSibling.innerHTML.substring(0,10); } } pp[i].innerHTML = ""; pp[i].appendChild(newBox); pp[i].appendChild(newBox2); pp[i].appendChild(btn); } } show(); </script>
本文网址:https://www.dedexuexi.com/wysj/javascript/3735.html
本站部分文章搜集与网络,如有侵权请联系本站,转载请说明出处。
标签: