1 问题描述 在制作网页时,若想让顶部的导航栏在页面整体滑动时,导航栏一直在顶部显示。 准备:引入element组件。 2 算法描述 使用addEventListener() 方法,进行事件监听,用于向指定元素添加事件句柄。 element.addEventListener(event, function, useCapture) 第一个参数是事件的类型 (如 "click" 或 "mousedown"); 注意:必须。字符串,指定事件名。不要使用 "on" 前缀。例如,使用 "click" ,而不是使用 "onclick"。 第二个参数是事件触发后调用的函数; 第三个参数是个布尔值用于描述事件是冒泡还是捕获。该参数是可选的。 具体看代码注释。 (一)template 代码清单 1 <template> <!-- 导航 --> <div class="Head "> <div class="navtop"> <img class="top_picture" src="./assets/9.jpg"> <el-button type="text" class="navbar">观光&活动</el-button> <el-button type="text" class="navbar">计划您的旅程</el-button> <el-button type="text" class="navbar navbar_1">旅游必备信息</el-button> </div> <div class="navend"> <el-button type="text" size="small"><i class="el-icon-search" style="color: black;margin-top: 12px;"><span> |</span></i></el-button> <el-button round size="small" style="background:rgba(218, 218, 218, 0.3);border:0px; "> 申请电子签证 </el-button> <el-button round size="small" type="success" round> 注册</el-button> </div> </div> </template> |
SCRIPT样式 代码清单 2 <script> import { videoPlayer } from 'vue-video-player' export default { name: 'VideoPlayer', } window.addEventListener('scroll', function() { /* 获取文档中 class="Head" 的元素:*/ let tou = document.querySelector('.Head'); /* tou.classList.toggle("bian",window.scrollY>0); */ /* 使用此scrollY属性来检查使用相对滚动函数(例如,scrollBy(),scrollByLines()或scrollByPages())时文档是否已滚动。*/ if (window.scrollY > 0) { // classListAPI提供了原生的方式来添加,删除,切换,或检查CSS类存在的元素
/* classList.add() 添加类名 */ tou.classList.add("bian"); /* bian 为导航栏滑动时设置的类名 */ } else { tou.classList.remove("bian"); } }) </script> |
CSS样式 代码清单 3 <style> /* 导航栏 */ .Head { width: 100%; height: 50px; position: fixed; top: 0; left: 0; right: 0; justify-content: space-between; align-items: center; transition: 0.5s; display: flex; z-index: 3; } .navtop { width: 70%; float: left; } .navend { width: 30%; float: right; } .top_picture { position: relative; width: 30px; height: 30px; padding-left: 20px; padding-top: 10px; } /* 导航栏 滑动时的样式设置*/ .bian { background-color: rgb(255, 255, 255); } .bian .Head { color: rgb(0, 0, 0); } .navbar { margin-left: 10px; padding-right: 30px; margin-top: 2px; color: #000000; } .el-button:hover { color: #e9e9e9; } </style> |
具体效果: 3 结语 本篇文章主要讲的是通过添加addEventListener()方法来对导航栏滑动时进行样式的设置。在本次实验中的图片未能很好的使其进行居中。本篇文章并未完全讲完关于addEventListener()方法的参数,但可以通过教程查看其他消息,同时若想移除 addEventListener() 方法添加的事件句柄则使用 removeEventListener() 方法来移除。 实习编辑:衡辉
|