2012-12-10 58 views
0

我有一个div,通过CSS悬停展开。当用户点击div时,我希望它保持在这个宽度。到目前为止,我有这个工作。悬停时切换宽度,保持点击,释放点击并点击关

但是,当用户再次单击div(切换)并且用户单击文档其余部分的div时,我需要将div折叠回原始大小。

Fiddle is here

jQuery的位置:

$(".rail").click(function() { 
    $(".rail").width(180); 
}); 

此处的CSS:

.rail{ 
    width: 30px; 
    border-left: 10px solid #ff5400; 
    position: absolute; 
    top: 0px; 
    bottom: 0px; 
    right: 0px; 
    background-color: rgba(0,0,0,0.15); 
    cursor: pointer; 
    -webkit-transition: all .3s ease-in-out; 
    -moz-transition: all .3s ease-in-out; 
    -o-transition: all .3s ease-in-out; 
    transition: all .3s ease-in-out; 
} 
.rail:hover{ 
    width: 180px; 
    background-color: #ddd; 
    -webkit-transition: all .3s ease-in-out; 
    -moz-transition: all .3s ease-in-out; 
    -o-transition: all .3s ease-in-out; 
    transition: all .3s ease-in-out; 
} 

回答

1
$(".rail").on({ 
    mouseenter: function() { 
     $(this).addClass('hover'); 
    }, 
    mouseleave: function() { 
     $(this).removeClass('hover'); 
    }, 
    click: function() { 
     $(this).toggleClass('active'); 
    } 
}); 

$(document).on('click', function(e) { 
    if (!$(e.target).is('.rail') && $('.rail').is('.active')) $('.rail').removeClass('active'); 
}); 

FIDDLE

+0

不知道为什么这是公认的答案。这是复杂的两倍。 :\ – teh1

+0

@ teh1 - 并非如此,我只是在jQuery中做了悬停的东西,因为我喜欢将它全部放在一个地方,如果删除了悬停功能,它几乎和你的答案一样。 – adeneo

+0

虽然这是非常侵扰性的。拿出jQuery将彻底打破它。使用我的方法,它将完全起作用,除非在没有jQuery的情况下单击时展开。别担心。 – teh1

2

给你。我更新了那个小提琴。

http://jsfiddle.net/ZfKYr/8/

我改变的是:

1.) Added a '.rail-sticky' rule that forces the rail open. 
2.) Changed the click function to toggle that rule instead of forcing it open. 

HTML:

<div class="rail"> 

</div>​ 

的JavaScript:

$(".rail").click(function() { 
    $(".rail").toggleClass('rail-sticky'); 
    return false; 
}); 

$(document).on('click',':not(.rail)',function() 
{ 
    $('.rail').removeClass('rail-sticky'); 
}); 

CSS:

.rail{ 
    width: 30px; 
    border-left: 10px solid #ff5400; 
    position: absolute; 
    top: 0px; 
    bottom: 0px; 
    right: 0px; 
    background-color: rgba(0,0,0,0.15); 
    cursor: pointer; 
    -webkit-transition: all .3s ease-in-out; 
    -moz-transition: all .3s ease-in-out; 
    -o-transition: all .3s ease-in-out; 
    transition: all .3s ease-in-out; 
} 
.rail:hover{ 
    width: 180px; 
    background-color: #ddd; 
    -webkit-transition: all .3s ease-in-out; 
    -moz-transition: all .3s ease-in-out; 
    -o-transition: all .3s ease-in-out; 
    transition: all .3s ease-in-out; 
} 

.rail-sticky 
{ 
    width: 180px; 
}​ 
+0

不得不把它交给adeneo,让我在页面的其余部分点击关闭功能。 – ryanSrich

+0

啊。我错过了那部分。反正我会更新我的帖子。 – teh1