2017-03-06 17 views
1

ご覧のとおり、リストとボタンがあります。ボタンでトリガされた「クリック」イベントが発生すると、新しい要素を動的にリストに追加します。新しい要素がリストに追加された後、javascriptでホバー状態でアニメーションを作成したいが、それは機能していない。ハードコーディングされたリスト要素ですべてがうまくいきます。Css3動的追加要素がアニメーション化されない

第1の解決策は、リスト要素の最大数をハードコードし、何が不要なのかを隠すことです。しかし、もし私が要素の最大数を知らないのであれば?

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

関連する問題