简体   繁体   English

使用JavaScript保持水平滚动标题固定在顶部

[英]Keep horizontally scrolling header fixed on top using JavaScript

I'm trying to keep a header on top of the page using JavaScript. 我正在尝试使用JavaScript在页面顶部保留标题。 position: fixed cannot be used because the header needs to be scrolling horizontally. position: fixed因为标题需要水平滚动,因此无法使用。 Keeping it on top is easy but making it smooth is problematic. 将其保持在顶部很容易,但使其平滑则存在问题。 For some users it's smooth in Chrome but it's laggy on Safari for everyone. 对于某些用户来说,Chrome浏览器很流畅,但每个人的Safari浏览器都比较落后。

Here is an example: http://jsbin.com/bufejapuza/edit?html,css,js,output 这是一个示例: http : //jsbin.com/bufejapuza/edit?html,css,js,output

How do I keep the header fixed on top so that it won't be janky while scrolling. 我如何将标题固定在顶部,以免滚动时出现混乱。

Edit: To get it lagging in Chrome, try toggling the HTML, CSS & JS tabs in JSBin. 编辑:要使其滞后于Chrome,请尝试在JSBin中切换HTML,CSS和JS标签。

Use position fixed and adjust X dynamically, not Y 使用固定位置并动态调整X,而不是Y

  • Change header position to fixed 将标题position更改为fixed
  • Adjust the x-pos by JavaScript 通过JavaScript调整x-pos
  • No jank while scrolling vertically 垂直滚动时无杂音
function setLocation() {
  var left = -window.scrollX;  
  header.style.transform = "translateX(" + left + "px)";
}

I tested this in Firefox and Safari (both Mac) and it fixed the problem. 我在Firefox和Safari(均为Mac)中进行了测试,并解决了该问题。

Modified JS Bin 修改后的JS Bin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM