如何修改代码实现点击Div区域或内部按钮均可显示更多文本功能
Hey there! I see you want to make both the button and the entire div trigger the read more/less toggle, with unified logic. Let's adjust your code to make that happen smoothly.
Key Changes Needed
- Add a click event listener to the
.glide__slidediv itself - Refactor the
ReadMorefunction to work with both div and button triggers (no more relying on fragilepreviousElementSiblingreferences) - Prevent event bubbling on the button so clicking it doesn't fire the div's click event twice
Updated HTML
<div class="glide__slide" onclick="ReadMore(event)"> <h3>Inka B.</h3> <p>Nádherné místo u lesa, ubytování v krásných, čistých zrenovovaných prostorách. Společná kuchyň velká se 3 linkami, 2 sporáky, 2 mikrovlnkami... když je více lidí, stále se dá vařit. A vedlejší jídelna pojme přes 20 lidí <span class="dots">...</span> <span class="more">- ideální i na rodinnou oslavu. Postele pohodlné, pokoje útulné...a ten výhled z terasy! Na všem se dalo domluvit...zkrátka, vracíme se zpět! Cítili jsme se tu opravdu vítání. Děkujeme!</span> </p> <button onclick="ReadMore(event)" class="myBtn">Read more</button> </div>
Updated JavaScript
function ReadMore(event) { // Stop button click from bubbling up to the div (prevents double execution) if (event.target.classList.contains('myBtn')) { event.stopPropagation(); } // Find the parent slide div no matter if we clicked the div or the button const slideDiv = event.target.closest('.glide__slide'); const dots = slideDiv.querySelector(".dots"); const moreText = slideDiv.querySelector(".more"); const btnText = slideDiv.querySelector(".myBtn"); // Get the button directly from the slide if (dots.style.display === "none") { dots.style.display = "inline"; btnText.innerHTML = "Read more"; moreText.style.display = "none"; } else { dots.style.display = "none"; btnText.innerHTML = "Read less"; moreText.style.display = "inline"; } }
CSS (Unchanged)
.more { display: none; }
How It Works
- Div Click Handling: We added
onclick="ReadMore(event)"to the.glide__slidediv, so clicking anywhere in the div (except the button) triggers the toggle. - Unified Element Selection: Using
closest('.glide__slide')ensures we always find the correct parent container, regardless of whether the trigger was the div or the button. This makes the code far more robust than relying on sibling element references. - Prevent Double Execution: When the button is clicked,
event.stopPropagation()stops the click event from bubbling up to the div, so the function only runs once. - Button Text Sync: We directly select the button from the slide div, so even if you click the div itself, the button text updates correctly to match the current state.
内容的提问来源于stack exchange,提问作者kebabdude
相关产品推荐
相关产品推荐

