点击文本切换登录与注册div显示/隐藏的技术实现问询
实现登录/注册面板切换功能
需求说明
我有两个div(类名分别为login和signup),分别对应登录和注册面板:
- 登录
div内有一段带下划线的“注册”文本 - 注册
div内有一段带下划线的“登录”文本
要求点击这些文本时,隐藏当前面板,显示另一个面板。
现有HTML代码
<div class="login"> <h2 class="textHead">MedConnect</h2> <h2 class="logintxt">登录您的账户</h2> <input type="text" class="loginemailtxt" name="email" placeholder="邮箱地址"> <input type="password" class="loginpwdtxt" name="password" placeholder="密码"> <button class="loginbtn" type="button" name="button">登录</button> <h5 id="signuptext" style="margin-top: 50px; text-align: center;">还没有账户?<u style="cursor: pointer;">注册</u></h5> <h6 style="text-align: center;">点击“登录”,即表示您登录已有账户</h6> <div id="errorMsg"> <h5 id="loginNoEmail">请输入您的邮箱地址</h5> <h5 id="loginNoPassword">请输入您的密码</h5> <h5 id="loginIncorrectCreds">邮箱或密码错误</h5> </div> </div> <div class="signup" style="display: none"> <h2 class="textHead">MedConnect</h2> <h2 class="logintxt">创建新账户</h2> <input type="text" class="signupnametxt" name="Name" placeholder="姓名"> <input type="text" class="signupemailtxt" name="Email" placeholder="邮箱地址"> <input type="password" class="signuppwdtxt" name="Password" placeholder="设置密码"> <button class="signupbtn" type="button" name="Button">注册</button> <h5 id="logintext" style="margin-top: 50px; text-align: center;">已是会员?<u style="cursor: pointer;">登录</u></h5> <h6 style="margin-top: 5px; text-align: center;">点击“注册”,即表示您同意我们的<u style="cursor: pointer;">条款</u>和<u style="cursor: pointer;">隐私政策</u></h6> <div id="errorMsg"> <h5 id="loginNoEmail">请输入您的邮箱地址</h5> <h5 id="loginNoPassword">请输入您的密码</h5> <h5 id="loginIncorrectCreds">邮箱或密码错误</h5> </div> </div>
实现切换的JavaScript代码
通过添加点击事件监听,修改元素的display属性完成面板切换:
<script type="text/javascript"> var signuptxt = document.getElementById('signuptext'); var logintxt = document.getElementById('logintext'); // getElementsByClassName返回元素集合,取第一个目标元素 var loginDiv = document.getElementsByClassName('login')[0]; var signUpDiv = document.getElementsByClassName('signup')[0]; // 点击登录面板的注册文本,切换到注册面板 signuptxt.addEventListener('click', function() { loginDiv.style.display = 'none'; signUpDiv.style.display = 'block'; }); // 点击注册面板的登录文本,切换到登录面板 logintxt.addEventListener('click', function() { signUpDiv.style.display = 'none'; loginDiv.style.display = 'block'; }); </script>
关键说明
getElementsByClassName返回的是HTMLCollection类型的元素集合,需要通过[0]获取对应的单个面板元素- 通过设置
style.display为none隐藏当前面板,设置为block显示目标面板,实现切换效果
内容的提问来源于stack exchange,提问作者aarushDagoat
相关产品推荐
相关产品推荐

