如何实现点击按钮时显示指定段落?
实现点击按钮显示指定段落的技术方案
要实现点击按钮显示指定段落的功能,核心思路是让目标段落默认隐藏,再通过JavaScript监听按钮的点击事件触发显示操作。以下是几种实用的实现方案:
方案一:原生JavaScript基础实现
先让段落默认隐藏,点击按钮后直接修改元素样式显示段落:
<button class="con-button" type="button">SUMBIT</button> <!-- 给段落添加默认隐藏样式 --> <p id="d-c" class="d-c" style="display: none;">Thanks for contacting <strong>Deni Beatz</strong>,your message has been sent 6 <u>Reply of Deni Beatz will be send you on mail with <strong>Contact</strong> on fastest type possible</u></p> <script> // 获取按钮和目标段落元素 const submitBtn = document.querySelector('.con-button'); const messagePara = document.getElementById('d-c'); // 绑定点击事件 submitBtn.addEventListener('click', function() { // 将段落设置为显示状态(若段落是行内元素可改用inline) messagePara.style.display = 'block'; }); </script>
方案二:支持切换显示/隐藏的实现
如果需要点击按钮能来回切换段落的显示/隐藏状态,可使用以下代码:
<button class="con-button" type="button">SUMBIT</button> <p id="d-c" class="d-c" style="display: none;">Thanks for contacting <strong>Deni Beatz</strong>,your message has been sent 6 <u>Reply of Deni Beatz will be send you on mail with <strong>Contact</strong> on fastest type possible</u></p> <script> const submitBtn = document.querySelector('.con-button'); const messagePara = document.getElementById('d-c'); submitBtn.addEventListener('click', function() { // 判断当前状态并切换 messagePara.style.display = messagePara.style.display === 'none' ? 'block' : 'none'; }); </script>
方案三:CSS类控制(更易维护的方式)
将样式逻辑与JavaScript分离,通过添加/移除CSS类来控制显示状态:
<style> /* 默认隐藏段落 */ .d-c { display: none; } /* 定义显示状态的类 */ .show-paragraph { display: block; } </style> <button class="con-button" type="button">SUMBIT</button> <p id="d-c" class="d-c">Thanks for contacting <strong>Deni Beatz</strong>,your message has been sent 6 <u>Reply of Deni Beatz will be send you on mail with <strong>Contact</strong> on fastest type possible</u></p> <script> const submitBtn = document.querySelector('.con-button'); const messagePara = document.getElementById('d-c'); submitBtn.addEventListener('click', function() { // 添加显示类(若需要切换状态,改用messagePara.classList.toggle('show-paragraph')) messagePara.classList.add('show-paragraph'); }); </script>
内容的提问来源于stack exchange,提问作者Deni Beatz
相关产品推荐
相关产品推荐

