嘿,我遇到了一个看似简单的问题,但遇到了一些麻烦。当我点击汉堡包切换菜单的 X 时,我只想显示一次警告消息。感谢您的帮助。
这是我在代码笔中引用的代码:https://codepen.io/toshvelaga/pen/wLJYKL
我曾尝试使用下面的代码,但我收到了两次警告消息,并且在单击汉堡包而不是仅单击 X 时也收到了警告消息。
$(document).ready(function(){
$('#nav-icon3').click(function(){
$(this).toggleClass('open');
$('#nav-icon3.open').click(function() {
alert("hello");
});
});
});
最佳答案
检查元素是否在(单个)处理程序中有 open
类,如果有,记录 hello
:
$('#nav-icon3').click(function() {
if (this.matches('.open')) {
console.log("hello");
}
$(this).toggleClass('open');
});
/* Icon 3 */
#nav-icon3 {
width: 60px;
height: 45px;
position: relative;
margin: 50px auto;
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
-webkit-transition: .5s ease-in-out;
-moz-transition: .5s ease-in-out;
-o-transition: .5s ease-in-out;
transition: .5s ease-in-out;
cursor: pointer;
}
#nav-icon3 span {
display: block;
position: absolute;
height: 9px;
width: 100%;
background: #d3531a;
border-radius: 9px;
opacity: 1;
left: 0;
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
-webkit-transition: .25s ease-in-out;
-moz-transition: .25s ease-in-out;
-o-transition: .25s ease-in-out;
transition: .25s ease-in-out;
}
#nav-icon3 span:nth-child(1) {
top: 0px;
}
#nav-icon3 span:nth-child(2),
#nav-icon3 span:nth-child(3) {
top: 18px;
}
#nav-icon3 span:nth-child(4) {
top: 36px;
}
#nav-icon3.open span:nth-child(1) {
top: 18px;
width: 0%;
left: 50%;
}
#nav-icon3.open span:nth-child(2) {
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
}
#nav-icon3.open span:nth-child(3) {
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
}
#nav-icon3.open span:nth-child(4) {
top: 18px;
width: 0%;
left: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="nav-icon3">
<span></span>
<span></span>
<span></span>
<span></span>
</div>
关于javascript - 如何通过 Javascript 中的切换类选择元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56712800/