我遇到classList.add javascript函数的问题。 我想添加"活跃" class into元素并为这些活动类应用css样式。但是,它似乎没有用,我很难用它。 任何人都可以帮我解决这个问题吗? 下面是我的HTML文件的当前部分和与此javascript对应的css部分。
部分:
<script>
function debounce(func, wait = 20, immediate = true) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
const sliderImages = document.querySelectorAll('.slide-in');
function checkSlide(e) {
sliderImages.forEach(sliderImage => {
const slideInAt = (window.scrollY + window.innerHeight) - sliderImage.height / 2;
const imageBottom = sliderImage.offsetTop + sliderImage.height;
const isHalfShown = slideInAt > sliderImage.offsetTop;
const isNotScrolledPast = window.scrollY < imageBottom;
if(isHalfShown && isNotScrolledPast) {
sliderImage.classList.add('active');
} else {
sliderImage.classList.remove('active');
}
})
}
window.addEventListener('scroll', debounce(checkSlide));
</script>
&#13;
与上述javascript对应的CSS部分:
.slide-in {
opacity: 0;
transition:all .5s;
}
.align-left {
float: left;
/*margin-right: 20px;*/
}
.align-right {
float: right;
/*margin-right: 20px;*/
}
.align-left.slide-in {
transform:translateX(-30%) scale(0.95);
}
.align-right.slide-in {
transform:translateX(30%) scale(0.95);
}
.slide-in.active {
opacity: 1;
transform: translateX(0%) scale(1);
}
&#13;
请帮我解决这个问题。
答案 0 :(得分:1)
classList功能没有任何问题,我在代码中做了一些更改,如下所示,
<script>
function debounce(func, wait , immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
const sliderImages = document.querySelectorAll('.slide-in');
function checkSlide(e) {
sliderImages.forEach(sliderImage => {
const slideInAt = (window.scrollY + window.innerHeight) - (sliderImage.clientHeight / 2);
const imageBottom = sliderImage.offsetTop + sliderImage.clientHeight;
const isHalfShown = slideInAt > sliderImage.offsetTop;
const isNotScrolledPast = window.scrollY < imageBottom;
if(isHalfShown && isNotScrolledPast) {
sliderImage.classList.add('active');
} else {
sliderImage.classList.remove('active');
}
})
}
var myEfficientFn = debounce(function() {checkSlide();}, 20,true);
window.addEventListener("scroll", myEfficientFn);
</script>
<script>
标记放在<body>
标记内。height
clientHeight
属性用法
window.addEventListener('scroll', debounce(checkSlide));
时,debounce函数在窗口加载时被调用使用了函数。当我们使用代码window.addEventListener("scroll", function(){return debounce(checkSlide);});
时,函数被分配给该事件,并在每次事件发生时被调用。