2017-01-29 56 views
1

所以我有这个元素#box需要有一个悬停效果,它可以在悬停时取代它自己。该元素将在jQuery中使用.hover正确悬停,然后我需要点击它来显示某些内容,但点击后它不应该有悬停效果,所以我使用.unbind将其删除。现在,当用户重新点击元素时,它将隐藏信息,然后重新应用悬停效果。所以就像一个切换效果。我的问题是什么是最干净的方式来做到这一点。单击jQuery后重新绑定悬停效果

HTML:

<div class="box" id="box"> 
    <h1 class="headline">ABOUT ME</h1> 
</div> 

CSS:

.box { 
height: 320px; 
width: 320px; 
background-color: rgba(0, 0, 0, 0.6); 
position: relative; 
left: 10px; 
top: 10px; 
transition: all 1s; 
-webkit-transition: all 1s; 
-moz-transition: all 1s; 
-o-transition: all 1s; 
} 

.headline { 
margin: 0 auto; 
color: white; 
text-align: center; 
display: block; 
padding-top: 130px; 
font-family: 'Montserrat', sans-serif; 
} 

.box_hover { 
left: 0px; 
top: 0px; 
height: 300px; 
width: 300px; 

}

JQuery的:

$(".box").hover(
    function() { 
    $(this).toggleClass("box_hover"); 
    } 
); 

$('#box').click(function() { 
    $(this).unbind('mouseenter mouseleave'); 
    }); 

这里是JSFiddle

编辑1:

为了澄清,我需要它来添加类时,其上空盘旋,然后当它的点击保持“的mouseenter”的出现,那么当其再次被点击回去能够被徘徊和基于“mouseenter”,“mouseleave”移动。

谢谢!

回答

1

其他然后解除绑定你可以使用一个布尔变量,click事件会触发,将控制是否toggleClass事件,被称为与否:

var bind = true; 
$(".box").hover(
    function() { 
    if(bind) $(this).toggleClass("box_hover"); 
    } 
); 

$('#box').click(function() { 
    bind = !bind; 
}); 

Fiddle Example

+0

非常简单,谢谢! – Jiroscopes

0

如果我理解正确的意图,你只需要切换上点击类以及:

$('#box').click(function() { 
    $(this).unbind('mouseenter mouseleave'); 
    $(this).toggleClass("box_hover"); 
}); 

Updated JSFiddle showcasing this

希望这会有所帮助!

编辑

根据链接将如何运作,你可以使用jQuery Mobile的弹出窗口,你就不需要更改绑定的。

你需要包括外部脚本:

<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"> 
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> 

而稍微改变你的HTML:

<div class="box" id="box"> 
    <h1 class="headline"><a href="#aboutme" data-rel="popup">ABOUT ME</a></h1> 
</div> 

<div data-role="popup" id="aboutme" class="ui-content"> 
    <h3>Welcome!</h3> 
    <p>Popup content</p> 
</div> 

随着你的CSS:

.headline a { 
    text-decoration: none; 
    color: inherit !important; 
} 

然后,对于jQuery,你可以简单地使用:

$('#box').click(function() { 
    $(this).toggleClass("box_hover"); 
}); 

我创建了一个新的JSFiddle展示here

+0

这使基于点击一次点击的运动。它需要悬停,然后当其点击删除悬停,然后当它重新点击应用悬停。所以它返回到原来的“预先点击”状态。 – Jiroscopes

+0

我已经更新了我的回答,展示了一个初始悬停的解决方案,在点击时失去悬停(并打开一个弹出窗口),然后在弹出窗口关闭时重新获得悬停:) –

0

当它具有.hover-effect类时,可以将该事件代入事件mouseenter/mouseleave。然后,您可以在单击该元素时切换该类。

这样,当元素拥有.hover-effect类,由于该类上点击切换,你基本上是结合并解除绑定每次点击悬停事件mouseenter/mouseleave事件才会被触发。

Updated Example

$(document).on('mouseenter mouseleave', '.box.hover-effect', function (event) { 
    $(this).toggleClass("box-hover", event.type === 'mouseenter'); 
}); 

$('.box').on('click', function() { 
    $(this).toggleClass('hover-effect'); 
});