我需要构建一个类似 jQuery Accordion 的效果。我有 10 个元素填满屏幕;当鼠标悬停在某个元素上时,该元素的宽度会扩大。如何使其从右向左展开最后 5 项?
我的 HTML :
<div class="wrap">
<div style="width: 165.25px; background: rgb(228, 228, 230);" class="item"></div>
<div style="width: 165.25px; background: rgb(35, 123, 192);" class="item"></div>
<div style="width: 165.25px; background: rgb(20, 4, 4);" class="item"></div>
<div style="width: 165.25px; background: rgb(182, 159, 36);" class="item"></div>
<div style="width: 165.25px; background: rgb(162, 169, 180);" class="item"></div>
<div style="width: 161px; background: rgb(37, 29, 4);" class="item"></div>
<div style="width: 161px; background: red;" class="item"></div>
<div style="width: 161px; background: rgb(88, 45, 45);" class="item"></div>
<div style="width: 161px; background: rgb(202, 41, 176);" class="item"></div>
<div style="width: 161px; background: rgb(24, 207, 185);" class="item"></div>
</div>
这是我的CSS:
.wrap{
width:100%;
float:left;
height: 300px;
overflow: hidden;
}
.item {
float:left;
height: 100%;
display: block;
}
jQuery 代码:
$('.item').each(function(e){
$(this).css('width', ($(this).parent().width()/10));
});
$('.item').on('mouseenter', function(event) {
$(this).stop().animate({width: "50%"}, {duration: 500});
}).on('mouseleave', function(event) {
$(this).stop().animate({width: ($(this).parent().width()/10)}, {duration: 500});
});
谢谢。
最佳答案
您需要在内部添加另一个宽度较大的包装器 div,以确保 float 元素不会换行到下一行。然后,当悬停元素为#5或更高时,将外包装div滚动到正确的位置:
$('.item').on('mouseenter', function(event) {
//Animate width
$(this).stop().animate({width: $(this).parent().parent().width()/2}, {duration: 500});
if($(this).index() >= 5){
//Animate scrollLeft
var marginLeft = $(this).parent().parent().width() / 10 * 4;
$(this).parent().parent().stop().animate({scrollLeft: marginLeft + 'px'}, {duration: 500});
}
}).on('mouseleave', function(event) {
//Animate width
$(this).stop().animate({width: ($(this).parent().parent().width()/10)}, {duration: 500});
//Animate scrollLeft
$(this).parent().parent().stop().animate({scrollLeft: 0}, {duration: 500});
});
您可以在这里看到它的工作情况:jsFiddle link
关于jquery - CSS从右向左扩展宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26156674/