html 整屏幕显示,滑动切换
时间: 2023-07-20 17:40:04 浏览: 49
要实现整屏幕显示并且可以滑动切换的效果,可以使用CSS的`height: 100vh`来让页面占据整个视口高度,并且使用JavaScript来监听滑动事件,并且根据滑动的方向来切换页面。
HTML代码结构:
```html
<div class="section section1">
<h2>Section 1</h2>
<p>Content of section 1</p>
</div>
<div class="section section2">
<h2>Section 2</h2>
<p>Content of section 2</p>
</div>
<div class="section section3">
<h2>Section 3</h2>
<p>Content of section 3</p>
</div>
```
在上面的代码中,我们使用`<div>`元素来表示每个屏幕页面,并且使用`class`属性来区分不同的页面。
CSS样式:
```css
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.section {
height: 100vh;
overflow: hidden;
}
.section h2 {
font-size: 48px;
margin-top: 100px;
}
.section p {
font-size: 24px;
line-height: 1.5;
margin-top: 50px;
}
```
在上面的代码中,我们使用`html, body`选择器来让整个页面占据整个视口高度,并且去除默认的边距和内边距。然后我们使用`.section`类来设置每个页面的高度为整个视口高度,并且隐藏溢出部分。同时,我们设置了标题和内容的样式。
JavaScript代码:
```javascript
var sections = document.querySelectorAll('.section'); // 获取所有页面元素
var currentSectionIndex = 0; // 当前显示的页面索引
window.addEventListener('wheel', function(e) {
var direction = e.deltaY > 0 ? 1 : -1; // 判断滑动方向
scrollToSection(currentSectionIndex + direction);
});
function scrollToSection(index) {
if (index < 0 || index >= sections.length) {
return;
}
var targetPosition = index * window.innerHeight; // 计算目标位置
currentSectionIndex = index;
// 平滑滚动到目标位置
window.scrollTo({
top: targetPosition,
behavior: 'smooth'
});
}
```
在上面的代码中,我们首先使用`document.querySelectorAll`来获取所有的页面元素,然后使用`currentSectionIndex`变量来记录当前显示的页面索引。接着,我们使用`window.addEventListener`来监听鼠标滑动事件,并且根据滑动的方向来调用`scrollToSection`函数来切换页面。在`scrollToSection`函数中,我们首先判断目标索引是否越界,然后计算目标位置的垂直偏移量,并且使用`window.scrollTo`函数来平滑滚动到目标位置。
需要注意的是,如果要使用平滑滚动效果,需要在浏览器支持的情况下使用`behavior: 'smooth'`,否则会使用默认的瞬间跳转滚动效果。