2014-03-14 179 views
2

我想寫一個小腳本,執行以下操作;jquery懸停多個元素

我在一排上有三個圓圈。如果我徘徊,所有這三個人必須在彼此頂部向左滑動,並且我指向堆疊頂部。在這個例子中,藍色的。

之後,所有三個圈子都必須滑回原來的位置。

RGB example

這是我得到了什麼。是的,它正在工作,但...

  1. 它無法正常工作。
  2. 我想知道是否有更好的方法

$('.circle').hover(
    function(e){ 
     $(this).css({'z-index' : '99'}); 
     $('.circle').animate({'left' : '0px'},1000); 
    }, 
    function(e){ 
     $(this).css({'z-index' : '0'}); 
     $('.circle-red').animate({'left' : '0px'},1000); 
     $('.circle-blue').animate({'left' : '200px'},1000); 
     $('.circle-green').animate({'left' : '400px'},1000); 
    } 
); 
+1

它可能是一個很好的給一個jsfiddle示例 –

回答

1

的問題是,當圓移動遠離鼠標的鼠標離開功能被解僱。把所有的東西都轉移到你徘徊的圈子上會更有意義。這樣,當你離開圓圈時,它可以恢復正常。

不管怎樣,我的方法是在物體周圍創建容器,用來觸發它們回彈到位。看看這個小提琴:http://jsfiddle.net/cz366/2/

有一點要記住總是使用.stop()之前.animate()。這將阻止動畫排隊等待你。停止將清除/殺死元素上的動畫隊列。

+0

謝謝你的回答和你在jsfiddle中的例子。現在它工作正常。但爲了我個人的理解......仍然通過將數據添加到容器來了解腳本的工作原理和原因。 – Bastiaan

1

這是一個實現主要使用CSS轉換:

HTML

<div class="circles"> 
    <div class="circle"></div> 
    <div class="circle"></div> 
    <div class="circle"></div> 
</div> 

CSS

// Just basic looks. Notice the position: absolute; and the z-index defaulting to 0. 
.circles { 
    width: 300px; 
    position: relative; 
} 
.circle { 
    position:absolute; 
    display:inline-block; 
    z-index:0; 
    border-radius: 100px; 
    width: 100px; 
    height: 100px; 
    border: 2px solid #222; 
    transition: 500ms ease-in; 
} 
// Positioning for each one using the CSS3 nth-of-type pseudoselector. 
.circle:nth-of-type(1) { background:red; left: 0%} 
.circle:nth-of-type(2) { background:blue; left: 40%} 
.circle:nth-of-type(3) { background:yellow; left: 80%} 

// Matched items. jQuery will set all items' data-active attribute to the current active element. 
.circle:nth-of-type(1)[data-active="0"], 
.circle:nth-of-type(2)[data-active="1"], 
.circle:nth-of-type(3)[data-active="2"] { z-index: 2;} 

// We'll send all the circles to the same position depending on which is active 
.circle[data-active="0"] { left: 0%; } 
.circle[data-active="1"] { left: 40%; } 
.circle[data-active="2"] { left: 80%; } 

JS

$('.circle').on('mouseenter',function() { 
    var index = $('.circle').index($(this)); 
    $('.circle').attr('data-active', index); 
}); 

$('.circle').on('mouseleave',function() { 
    $('.circle').attr('data-active', ''); 
}); 

CODEPEN HERE

這是怎麼回事?

jQuery使用index()方法將當前索引設置爲[data-active](圓1爲0,圓2爲1,圓3爲2 - 注意數字的差異)。

我們使用:nth類型的CSS3僞選擇器來匹配data-active屬性。如果圈1有[data-active=0],那麼我們將給它一個2的z-索引,這樣它可以在最上面。

所有帶有data-active=0的項目都將移動到圓圈1的相同位置:剩餘10%。所有數據激活= 1的項目將移動到左側:40%等等。

注意:爲了額外的樂趣,添加transform:rotateY(180deg);之後的z-index:2;屬性。

該運動是與過渡:500毫秒緩入;屬性,並在left屬性更改時自動對動畫進行排序。

這可能更簡潔,但代碼的結構方式,我認爲它更容易理解。

+0

很好的答案,但是能夠很好的解釋你到底在做什麼;) –

+0

到目前爲止,我看到了圓翻轉,它變成了白色。想要使顏色保持不變,並使其與OP所具有的一樣:3個圓圈彼此重疊,但略有偏移,以便看到第1,2和3層? –