元素锁定滚动纯JavaScript没有Jquery

时间:2017-07-20 14:40:28

标签: javascript html css scroll parallax

enter image description here我试图将绿色框锁定到用户滚动内容时的最顶部。但是,当您滚动时,绿色框顶部会有一个间隙(如演示中所示)

我试图将位置固定为绿色框,但它跳出红色框。所以它需要保持绝对。

请查看我在此处设置的示例http://jsfiddle.net/jpXjH/839/

或者看看这里的代码

<div style="padding: 20px 0px; background-color:cyan;">
    This is a header with some random content
</div>

  <div style="width:480px; height:1400px; overflow:hidden; margin:auto; 
   border:1px solid gray; position:relative; background-color: #ff5d5d; ">

      <div id="locked">
         This element needs to be on the very top LOCKED when scrolled down. 
         However you can see there is a gap in the very top when you scroll.
      </div>

</div>

<style>
#locked{
    background-color: limegreen;
    padding:10px;
    width:150px;
    position:absolute;
    top:0;
    right:0;
}
</style>
<script>
    window.onscroll = changePos;

            function changePos() {
                var locked = document.getElementById("locked");

                if (window.pageYOffset > 30) {
                    locked.style.position = "absolute";
        locked.style.float = "right";
                    locked.style.top = pageYOffset + "px"
                } else {
                    locked.style.position = "";
                    locked.style.top = "";
                }
            }
<script>

提前致谢

3 个答案:

答案 0 :(得分:0)

我能想到的最简单的解决方案是从你在JS中改变的header.style.top中减去顶部锁定条的高度:

header.style.top = pageYOffset - 76 + "px"
显然你可以直接从元素获得高度而不是硬编码。

答案 1 :(得分:0)

你的身体或html标签上可能有一些填充/边距。检查它是否存在,然后通过减去window.pageYOffset global中的金额来计算它。

您还需要考虑红色div之前的任何元素的高度。

答案 2 :(得分:0)

为什么你不尝试使用固定位置,例如:

[standalone@localhost:9990 /] 
/subsystem=keycloak/securedeployment=my.war/:add(realm=bkofc,auth-server-
url=http://192.168.99.100/30001/auth, bearer-only=true, ssl-
required=EXTERNAL, resource=bkofc-svc, use-resource-role-mappings=true, 
credential=9bcc6d9f-9c72-4b58-b297-79f0f207d9e1)


'credential' is not found among the supported properties: [allow-any-
hostname, always-refresh-token, auth-server-url, auth-server-url-for-
backend-requests, autodetect-bearer-only, bearer-only, client-key-password, 
client-keystore, client-keystore-password, connection-pool-size, cors-
allowed-headers, cors-allowed-methods, cors-max-age, disable-trust-manager, 
enable-basic-auth, enable-cors, expose-token, min-time-between-jwks-
requests, principal-attribute, public-client, realm, realm-public-key, 
register-node-at-startup, register-node-period, resource, ssl-required, 
token-minimum-time-to-live, token-store, truststore, truststore-passw
ord, turn-off-change-session-id-on-login, use-resource-role-mappings]
[standalone@localhost:9990 /]

如果你和红色容器对齐,你可以用JS计算。