这是我的密码:
$(document).ready(function () {
if($('#first-item').hasClass('active'){
$( ".go-prev" ).addClass( "hideMe" );
} else {
$( ".go-prev" ).removeClass( "hideMe" );
}
})
此代码只工作一次,当我滚动到下一页(幻灯片)时,它不会删除活动类,解决方案是什么?
发布于 2022-08-20 19:32:03
根据我的评论:
$(document).ready(() => {
//we define our observed element
const observedElement = document.getElementById("first-item");
//we create an observer and pass a callback function..
new MutationObserver(mutationCallback)
//and we set it to observe,a specific element's mutations
.observe(observedElement, {
attributes: true,
attributeFilter: ["class"],
});
//it will run the callback function everytime it detects a mutation on the observed element..
//such as change of classlist items etc..
});
const mutationCallback = () => {
if ($("#first-item").hasClass("active")) {
$(".go-prev").addClass("hideMe");
} else {
$(".go-prev").removeClass("hideMe");
}
};
//lets make a mutation to observed element to see if it works
const testMutation = () => {
$("#first-item").addClass("active");
}
.hideMe{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="first-item">OBSERVED ELEMENT</h1>
<h1 class="go-prev">AFFECTED ELEMENT</h1>
<button onclick="testMutation()">TEST</button>
了解更多关于MutationObserver的信息
https://stackoverflow.com/questions/73423573
复制相似问题