首页 > 解决方案 > Accelerated Mobile Pages(AMP) 如何制作固定页眉?

问题描述

问题仅属于 AMP。我相信这个引用简单的问题。曾尝试为元素固定位置,它在 js 控制台中显示警告,并且标题移动了几个像素远离它应该在的位置。我看过示例,但是代码/样式太多,所以不明白他们是如何完成这项任务的。

我需要在滚动页面时将元素固定在顶部,这个元素包含两个按钮 - 菜单和共享以及网站标题,如果按钮可以向左/向右浮动就好了。

我在普通页面上没有类似问题,无论是移动设备还是桌面设备,但我是 AMP 的新手。

标签: amp-html

解决方案


我在那里找到了一个解决方案:https ://amp-demos.glitch.me/sticky-header.html 它与我需要的不同,它根据文章的一部分选择菜单项,目前使用动画和观察者插件阅读。但是我发现它很容易修改。在我的示例菜单中,它应该移动,并且有子菜单项。删除动画,很容易赌回来,只需比较两个版本。

CSS:

:root {
  --header-height: 3em;
}
.sticky-header {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  left: 0;
  right: 0;
  height: var(--header-height);
  z-index: 1000;
}
.sticky-header .item {
  position: relative;
}
.sticky-header .item > * {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  line-height: var(--header-height);
}

.sticky-header .item .selected {
  opacity: 0;
}

/* move anchor sections below the sticky header */
:target {
  display: block;
  position: relative;
  top: calc(-1 * var(--header-height) - 8px);
  visibility: hidden;
}

/* general styling */
h1 {
  text-align: center;
}
h1, main {
  margin: 1rem;
}
a, a:visited {
  color: inherit;
  text-decoration: inherit;
  background-color: inherit;
}
.sticky-header {
  display: flex;
  align-items: center;
  justify-content: space-around;
  background-color: inherit;
}
.sticky-header .item {
  height: 100%;
  width: 100%;
}
.sticky-header .item > * {
  text-align: center;
  color: inherit;
}
.sticky-header .item .selected {
  color: red;
}
.submenu {
  display:none;
}
.item:hover .submenu {
  display:  block;
  position: relative;
  top: var(--header-height);
  line-height: 2em; //calc(1em + 12px);
  background: black;
}
.item:hover .submenu a {
  display: block;
}

Html 部分,简化:

<div class="sticky-header">
  <div class="item" tabindex="0" role="button">
    <a href="#item1">Item 1</a>
    <div class="submenu">
      <div tabindex="0" role="button"><a href="#s1">Sub menu</a></div>
      <div><a href="#s2">Sub menu</a></div>
      <div><a href="#s3">Sub menu</a></div>
    </div>
  </div>
  <div class="item" tabindex="0" role="button">
    <a href="#item2">Item 2</a>
  </div>
  <div class="item" tabindex="0" role="button">
    <a href="#item3">Item 3</a>
  </div>

@Ryan 在评论中提供了他自己的方法,但我发现很难检查网站是否需要代码,然后只是一个简单的小例子。


推荐阅读