简体   繁体   English

DOM:查找 html 元素的当前滚动上下文

[英]DOM: Finding the current scroll context of an html element

Let's say I have the following document:假设我有以下文件:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <div class="scrollcontainer">
    ...
    <div class="content"></div>
    ...
  </div>
  ...
</body>
</html>

And .scrollcontainer is a scrollable div : .scrollcontainer是一个可滚动的div

.scrollcontainer {
    overflow-y: scroll;
}

Is there any way to find .scrollcontainer as the current "scroll context" (aka the parent scrollable element) for .content ?有没有办法找到.scrollcontainer作为当前“滚动语境”(又名父滚动的元素) .content

I'm looking something like:我看起来像:

// Should return the element `.scrollcontainer` in this example
document.querySelector('.content').scrollContext;

If there is a ancestor element with an overflow: scroll or overflow: auto , then it would be that element.如果有一个带有overflow: scrolloverflow: auto的祖先元素,那么它就是那个元素。 Otherwise the body/html (depending on the browser).否则为 body/html(取决于浏览器)。

Of course I could just add a data-attribute (eg data-scrollcontext ) to every scroll context and then find the closest parent with that attribute.当然,我可以向每个滚动上下文添加一个数据属性(例如data-scrollcontext ),然后找到具有该属性的最接近的父级。 But I'm curious to see if something like that is implemented in the DOM Api.但我很好奇是否在 DOM Api 中实现了类似的东西。

There is no DOM API to find out the scrollable container.没有 DOM API 来找出可滚动容器。 As here the difintion "scrollable" is missleading - should it be considered only by the css property , like overflow: scroll , even when it is not right now scrollable, or the css property plus the "scrollHeight > offsetHeight".由于这里的定义“可滚动”是误导性的 - 应该仅通过 css 属性来考虑它,例如overflow: scroll ,即使它现在不可滚动,或者 css 属性加上“scrollHeight > offsetHeight”。

You can create a custom function, which traverses the ancestors and checks the CSS properties, or you can implement any other logic here .您可以创建一个自定义函数,它遍历祖先并检查 CSS 属性,或者您可以在此处实现任何其他逻辑

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

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