2017-03-06 40 views
1

如您所見,我有列表和按鈕。當在按鈕上觸發「點擊」事件時,我會動態地將新元素添加到列表中。將新元素添加到列表後,我想使用JavaScript在懸停狀態下對其進行動畫處理,但它不起作用。一切都很好,硬編碼列表元素。Css3動態添加元素未獲得動畫

想到的第一個解決方案是硬編碼列表元素的最大數量,當隱藏什麼是不必要的。但是,如果我不知道元素的最大數量呢?

Here is code

的Html

<section> 
    <div class='wrap'> 
    <ul> 
     <li class="box"></li> 
     <li class="box stacked"></li> 
    </ul> 
    </div> 
    <button> addBox </button> 
</section> 

CSS /薩斯

.box 
    width: 100px 
    height: 100px 
    border: 1px solid black 
    background: orange 
    flex-basis: 1 

.stacked 
    margin-left: -50px 

.up 
    animation-name: boxUp 
    animation-duration: 300ms 
    animation-timing-function: ease-in-out 
    animation-delay: 0s 
    animation-iteration-count: 1 
    animation-direction: normal 
    animation-fill-mode: forwards 


@keyframes boxUp 
    from 
    transform: translate(0, 0) 
    to 
    transform: translate(0, -25px) 

的Javascript

$('button').click(function(e) { 
    $('ul').append($('<li>').attr('class', 'box stacked')); 
}); 

$('.box').hover(function() { 
    $(this).addClass('up'); 
}, function(){ 
    $(this).removeClass('up'); 
}); 
+1

使用委派它是一個動態添加的元素。 – Harry

+0

謝謝。找到了解決方案。 $('ul')。on('mouseenter mouseleave','li',function(){ $(this).toggleClass('up'); }); – user7666810

+0

是的,發佈答案 – user7666810

回答

1

既然是動態添加元件,但是不存在於該在附加事件處理程序時的DOM。因此,您必須從一開始就使用DOM中存在的父代(也就是說,使用頁面的靜態內容的父代,並且從加載時直接出現)使用代理。

您可以使用任一下面:

$('body').on('mouseenter mouseleave', `.box`, function() { 
    $(this).toggleClass('up'); 
}); 

或低於你最終使用的一個:如果

$('ul').on('mouseenter mouseleave', 'li', function(){ 
    $(this).toggleClass('up'); 
}); 

CodePen Demo