1
ご覧のとおり、リストとボタンがあります。ボタンでトリガされた「クリック」イベントが発生すると、新しい要素を動的にリストに追加します。新しい要素がリストに追加された後、javascriptでホバー状態でアニメーションを作成したいが、それは機能していない。ハードコーディングされたリスト要素ですべてがうまくいきます。Css3動的追加要素がアニメーション化されない
第1の解決策は、リスト要素の最大数をハードコードし、何が不要なのかを隠すことです。しかし、もし私が要素の最大数を知らないのであれば?
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');
});
使用委任それが動的に追加された要素である場合。 – Harry
ありがとうございます。解決策を見つけました。 $( 'ul')。on( 'mouseenter mouseleave'、 'li'、function(){ $(this).toggleClass( 'up'); }); – user7666810
はい、その回答を投稿してください – user7666810