基于onclick事件的「显示更多」内容框功能失效求助
修复「显示更多」内容框的功能问题
你的代码存在三个关键问题,导致功能失效:
- CSS选择器错误:原代码中
#idOfcontent .classOfopen的空格表示选择#idOfcontent内部的子元素,但实际需要给内容容器自身添加类,应改为#idOfcontent.classOfopen(移除空格)。 - CSS笔误:按钮样式里的
font-size: 17pxx多了一个冗余的x,修正为font-size: 17px;同时background: #ffff多了一个f,规范写法为#fff。 - JavaScript逻辑不健壮:用
className == "classOfopen"判断类名,无法兼容元素存在多个类的场景,且直接清空className会丢失原有类(哪怕当前没有)。推荐使用classListAPI来安全地添加、移除和检测类。
修正后的完整代码
JavaScript
let contentVar = document.getElementById("idOfcontent"); let buttonVar = document.getElementById("idOfshowmore"); buttonVar.onclick = function() { if (contentVar.classList.contains("classOfopen")) { // 收起内容 contentVar.classList.remove("classOfopen"); buttonVar.innerHTML = "Show More"; } else { // 展开内容 contentVar.classList.add("classOfopen"); buttonVar.innerHTML = "Show Less"; } }
CSS
body { background: #eee; } #idOfcontent { width: 400px; background: #fff; padding: 18px; font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 18px; color: #444; margin: 0 auto; max-height: 100px; overflow: hidden; transition: max-height 0.7s; -webkit-transition: max-height 0.7s; -moz-transition: max-height 0.7s; } #idOfcontent.classOfopen { max-height: 5000px; transition: max-height 0.7s; -webkit-transition: max-height 0.7s; -moz-transition: max-height 0.7s; } #idOfshowmore { background: #1594e5; color: #ffffff; font-family: Verdana, Geneva, Tahoma, sans-serif; display: block; width: 140px; font-size: 17px; text-transform: uppercase; padding: 10px; text-align: center; margin: 20px auto; cursor: pointer; }
HTML
<div id="idOfcontent"> <p>In this JavaScript tutorial I want to run through a detailed example of how we can use the onclick event in JavaScript to create cool functionality on our websites.</p> <p> In this example I'll use the onclick event to create a 'show more' style content box which expands and shrinks as you click the button. </p> <p>The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. IDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more than one HTML element.</p> </div> <a id="idOfshowmore">Show More</a>
内容的提问来源于stack exchange,提问作者Lotus
相关产品推荐
相关产品推荐

