900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 仿小米导航栏;导航栏悬浮滚动更改背景色javascript实现;

仿小米导航栏;导航栏悬浮滚动更改背景色javascript实现;

时间:2020-01-02 08:49:45

相关推荐

仿小米导航栏;导航栏悬浮滚动更改背景色javascript实现;

一、实现效果

小米字体没引用,导航栏文字随便调的,仅供参考

二、代码

1、html

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href=""><title>小米</title><link rel="stylesheet" href="style.css"></head><body><!-- 导航栏 --><div class="bg1"><div class="head"><div class="main"><img src="./images/logo-mi2.png" alt=""><ul class="head-left"><li><a href="#">小米官网</a></li><li><a href="#">小米商城</a></li><li><a href="#">小米影像</a></li><li><a href="#">MIUI</a></li><li><a href="#">IoT</a></li><li><a href="#">云服务</a></li><li><a href="#">天星数科</a></li><li><a href="#">有品</a></li><li><a href="#">小爱开发平台</a></li><li><a href="#">企业团购</a></li></ul><ul class="head-right"><li><a href="#">登录</a></li><li>|</li><li><a href="#">注册</a></li></ul></div></div></div><div class="bg2"></div><!-- 回到顶部 --><div class="backtop"></div><script src="main.js"></script></body></html>

2、css

html,body {width: 100%;height: 100%;}li {list-style: none;}a {text-decoration: none;}* {margin: 0;padding: 0;}.head {position: fixed;background-color: transparent;top: 0;height: 65px;width: 100%;/* background-color: rgb(59, 55, 55); */line-height: 65px;}.head a {color: rgb(255, 255, 255);}.head a:hover {color: #ff6900;}.main {width: 1232.67px;margin: 0 auto;}.main img {float: left;width: 34px;height: 34px;margin-top: 15px;margin-right: 150px;}.head-left {float: left;}.head-right {float: right;}.head li {float: left;font-family: MiSans, serif;font-weight: 500;font-size: 14px;color: rgb(255, 255, 255);}.head-left>li {margin-right: 35px;}.head-right>li {margin-left: 25px;}.bg1 {width: 100%;background: url("./images/a1.png") no-repeat;background-size: 100% 100%;height: 560px;}/* 第二大部分 */.bg2 {width: 100%;height: 864px;background-color: lightgoldenrodyellow;}.backtop {position: fixed;display: none;bottom: 150px;right: 15px;width: 42px;height: 62px;background: url("./images/top-icon.png") no-repeat;background-size: 100% 100%;z-index: 1;}

3、javascript

var head = document.querySelector('.head');var backtop = document.querySelector('.backtop');function scroll() {let top = head.offsetTop;console.log(top);let scrollTop = document.documentElement.scrollTop;console.log(scrollTop);if (scrollTop <= top) {head.style.backgroundColor = 'transparent';backtop.style.display = 'none';} else {head.style.backgroundColor = 'rgba(34, 31, 31, .8)';backtop.style.display = 'block';}}// 每次屏幕滑动时都会检测到,调用scroll方法时刻更新导航栏背景色window.addEventListener('scroll', function () {scroll();})scroll();

三、文章参考

本文参考了

CSS布局——导航栏悬浮滚动更改背景色_qq591840685的博客-CSDN博客

js获取元素的滚动高度,和距离顶部的高度 - 梦幻飞雪 - 博客园 ()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。