我正在制作应该在滚动时淡入/淡出的div元素。我尝试使用onscroll,scroll,DOMMouseScroll,mousewheel以及jquery来简单地警告滚动(不褪色),但它并不适用于任何这些。仅适用于Chrome中的onmousewheel。
https://jsfiddle.net/643v7rod/
var el = document.getElementById('el');
var opacity = 1;
el.onmousewheel = function(e){
if(e.deltaY > 0){
opacity -= 0.25;
el.style.opacity = opacity;
}else{
opacity += 0.25;
el.style.opacity = opacity;
}
}
我在这里做错了什么?
答案 0 :(得分:1)
不推荐使用该鼠标事件,请参阅this
请尝试使用此功能,并确保您的div高度足以让您可以滚动:)
var el = document.getElementById('el');
var opacity = 1;
//if you want to be able to revert the effect, you will
//have to store the current window position
//in a variable and update it each time;
var position = window.scrollY;
//declaring the function
function effect(){
if(window.scrollY > position){
opacity -= 0.01;
el.style.opacity = opacity;
//now update the positoin
position = window.scrollY;
}else{
opacity += 0.01;
el.style.opacity = opacity;
//do it again
position = window.scrollY;
}
};
//adding the event listener
window.addEventListener("scroll", effect);

#el {
width: 300px;
height: 1200px;
background-color: red;
}

<div id="el"></div>
&#13;
我已经改变了不透明度,以便您清楚地看到效果。