嘿,我有一个看似简单的问题,但遇到了一些麻烦。当我点击汉堡切换菜单的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");
});
});
});
答案 0 :(得分:3)
检查元素在(单个)处理程序中是否具有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>
答案 1 :(得分:0)
我们将在第三个span
元素中添加一个 click 事件监听器,在这种情况下,X就是这个位置(我假设)。
$(document).ready(function() {
$('span:nth-child(3)').click(function () {
alert('X has been clicked')
})
});