javascript - 如何使标题仅在大屏幕上保持粘性,但在用户向下滚动时在移动设备上消失?
问题描述
这是一个网站:http ://samuelgoldwynfilms.com我想建立一个具有类似行为的标题。
在“samuelgoldwynfilms”网站上,菜单在移动设备上没有粘性,当用户在移动设备上向下滚动页面时它会消失,但在桌面屏幕上菜单是粘性的。它是如何变得粘稠的?我认为它是用 JavaScript 完成的。对?
请告诉我这个东西是怎么称呼的,因为我不知道,我什至无法在谷歌上寻找解决方案。我想知道他们实际上在 JavaScript 中检查了什么?是否可以检查窗口的宽度,然后基于此使菜单具有粘性?
这是我能做的最多的事情:
"use strict";
console.log("Hello");
:root {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
margin: 0;
padding: 0;
background: lightseagreen;
}
.header {
height: 150px;
background: #921801;
}
@media (min-width: 38em) {
body {
background: lightskyblue;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="header.css" rel="stylesheet">
<title>Header</title>
</head>
<body>
<header class="header">
</header>
<main>
<script>
for (let i = 0; i < 50; i++) {
document.write("<p>Text</p>");
}
</script>
</main>
<script src="header.js"></script>
</body>
</html>
解决方案
这是CSS的问题。您需要做的就是使用@media query
.
以下是几个案例:
对于粘性标题:
你可以使用位置:粘性;和顶部:0;
如果您的应用程序中有 js,您可以通过更改类 onscroll 为非粘性和粘性标题使用不同的类
@media screen and (min-width : 1024px /* your specific point : 1024 or 992 or 960 or ...in px */) {
/*
* Here is the code for Desktop
*
*/
}
@media screen and (max-width : 1024px /* 1024 or 992 or 960 or ... in px */) and (min-width : 768px) {
/*
* Here is the code for Tablet
*
*/
}
@media screen and (max-width : 767px ) {
/*
* Here is the code for mobile
*
*/
}
You can extend it with your taste.
推荐阅读
- c# - 在构造函数中投影时无法访问导航属性
- c++ - 在 C++ 结构中,构造函数中的默认值和默认参数有什么区别?
- java - 如何使用 Java 访问安装在 Windows 上的驱动器?
- angular - 在执行下一个函数之前,如何等待来自 Angular 引导模式窗口的响应?
- google-bigquery - 如何用有序数字替换列中的字符串?
- php - 我需要在计算机上隐藏 plist 文件
- python - 如何检查多个子字符串以获取python中的列名?
- hiveql - hive 1.1 中是否有任何日期函数来找出月份差异,如months_between 或 datediff(month,day1,day2)
- c++ - 语义操作后丢弃解析结果
- css - 在 Chrome 中的媒体查询中混合 calc 中的单位