如何仅在水平滚动后定位 div 元素?

How to position a div element only after having scrolled horizontally?

我正在寻找一种方法,仅在向右滚动大约 100% 后才将我页面的 #header 元素定位为 "fixed"。

如果剩余 < 100% 那么

#header { display:none; }

如果左 > 100% 那么

#header { position:fixed, top:0, left:0, width:50px, height:50px, color:red, z-index:9999; }

我试过了:

<script type='text/javascript'>
var header = $("#header");
$(document).scroll(function() {
    if($(this).scrollLeft() > 1920) {
        header.css({"position" : "fixed", "top" : "0", "left" : "0", "width" : "50px", "height" : "50px", "background" : "red", "z-index" : "9999"});
    } else {
        header.css({"display" : "none"});
}
});
</script>

但是没用。是否可以使用百分比而不是像素数量来设置条件? (100% 而不是 1920)

你能帮帮我吗?

尝试用 "window.innerWidth" 替换 1920。那是浏览器 window.

宽度的 JS DOM 变量