首页 > 解决方案 > 如何使标题仅在大屏幕上保持粘性,但在用户向下滚动时在移动设备上消失?

问题描述

这是一个网站: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>

标签: javascripthtml

解决方案


这是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.


推荐阅读