【发布时间】:2020-04-04 11:59:31
【问题描述】:
查看following example。我们有一个绿色块。纵向时,应固定在屏幕顶部。在横向时,它应该是静态的。有一些媒体查询可以控制这种行为。
将页面向下滚动到一定距离(无论它有多长),然后在 devtools 中将方向更改为横向,您会注意到屏幕跳到页面顶部。是什么导致这种情况发生?
如果您尝试手动更改 CSS 类以使块静态(我的意思是不改变方向),它不会跳到顶部。所以页面上有一个手动删除的按钮,试试看吧。
我还发现,如果你将这个绿色块的宽度更改为例如 10% 或给它“底部:0”,它不会导致屏幕跳跃。
它在 Chrome 中重现(macOS 和 Android,而不是在 iOS 上重现)
来自以上链接的示例代码:
document.addEventListener('DOMContentLoaded', () => {
const page = document.querySelector('.page');
const action = document.querySelector('.action');
action.onclick = () => {
page.classList.toggle('page_pinned');
};
});
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
}
body {
min-height: 5000px;
background-image: linear-gradient(to top, black, white);
}
.sticky {
width: 100%;
height: 200px;
}
.sticky {
background: green;
margin-top: 1px;
}
.action {
position: fixed;
bottom: 0;
left: 0;
padding: 10px;
font-size: 1.5em;
background: white;
border: 1px solid black;
}
@media (orientation: portrait) {
.page_pinned .sticky {
position: fixed;
}
}
@media (orientation: landscape) {
.page_pinned .sticky {
position: absolute;
}
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body>
<div class="page page_pinned">
<div class="sticky"></div>
</div>
<button class="action">Click me to toggle fixed/static positioning</button>
</body>
</html>
【问题讨论】:
-
这个问题很有吸引力。对于解决方案,我们可以使用 JavaScript 方向检测,然后为横向添加一个新类并更改位置。但是为什么滚动跳到顶部以及为什么它没有发生在我编辑的代码 sn-p 中?你可以测试一下。
标签: javascript html css google-chrome