我是CSS和HTML的新手。我正在尝试制作一页项目,但是当我用鼠标的滚轮向下滚动时,我不知道如何更改该部分。有人可以帮我吗?
代码如下:
section {
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
left: 0;
color: white;
background-color: black;
visibility: hidden;
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
section.active {
visibility: visible;
}
<section data-section="0" class="active">
<h1>hello! I'm the first section!</h1>
</section>
<section data-section="1">
<h2>Hello! I'm the second section!</h2>
</section>
<section data-section="2">
<h2>Hello! I'm the third section!</h2>
</section>
答案 0 :(得分:1)
我假设您希望单个滚轮刻度线与部分更改相对应。除了使用CSS滚动捕捉或jQuery之类的外部库之外,您还可以只使用滚轮侦听器来实现目标。
currentSectionIndex - 1 >= 0
和currentSectionIndex + 1 < sections.length
条件可防止后续的滚轮滚动超出HTML部分的数量。
由于提供的HTML和CSS不变,请参考所附的JavaScript作为解决方案。
let sections = document.getElementsByTagName('section');
// tracks index of current section
let currentSectionIndex = 0;
document.addEventListener('wheel', e => {
if (e.wheelDeltaY > 0 && currentSectionIndex - 1 >= 0) {
// wheel up
sections[currentSectionIndex].className = '';
currentSectionIndex--;
sections[currentSectionIndex].className = 'active';
} else if (e.wheelDeltaY < 0 && currentSectionIndex + 1 < sections.length) {
// wheel down
sections[currentSectionIndex].className = '';
currentSectionIndex++;
sections[currentSectionIndex].className = 'active';
}
});
section {
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
left: 0;
color:white;
background-color: black;
visibility: hidden;
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
section.active {
visibility: visible;
}
<section data-section="0" class="active">
<h1>hello! I'm the first section!</h1>
</section>
<section data-section="1">
<h2>Hello! I'm the second section!</h2>
</section>
<section data-section="2">
<h2>Hello! I'm the third section!</h2>
</section>
答案 1 :(得分:0)
我不是jQuery的佼佼者,但我希望这可以帮助:)
$(document).ready(function() {
$('#body').bind('mousewheel', function(e) {
if (e.originalEvent.wheelDelta / 120 > 0) {
var num = $('.active').attr('data-section');
num--;
if (num <= -1) {
num = num + 3;
}
$('.active').removeClass('active');
$('section[data-section="' + num + '"]').addClass('active');
} else {
var num = $('.active').attr('data-section');
num++;
if (num >= 3) {
num = 0;
}
$('.active').removeClass('active');
$('section[data-section="' + num + '"]').addClass('active');
}
});
});
body {
width: 100vw;
height: 100vh;
}
section {
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
left: 0;
color: white;
background-color: black;
visibility: hidden;
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
section.active {
visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<body id="body">
<section data-section="0" class="active">
<h1>hello! I'm the first section!</h1>
</section>
<section data-section="1">
<h2>Hello! I'm the second section!</h2>
</section>
<section data-section="2">
<h2>Hello! I'm the third section!</h2>
</section>
</body>