scrollTop 和 scrollLeft 不适用于 display:none 元素

scrollTop & scrollLeft do not work on display:none elements

本文关键字:none 元素 display 适用于 scrollLeft 不适用 scrollTop      更新时间:2023-09-26

我正在尝试在显示之前滚动隐藏元素。这是我正在使用的代码:

<div class="main">
    <div class="bg">
    </div>
</div>

.main { 
    display:none; 
    position:abolsute; 
    width:250px;height:250px; 
    overflow:scroll;
}
.bg { 
    background: blue url(http://defaulttester.com/img/bg-landing-mario.jpg); 
    width:1200px; 
    height:800px; 
}

$(".main").scrollTop($(".bg").height()/2);
$(".main").scrollLeft($(".bg").width()/2);

如果显示它,它工作正常,但如果它display:hidden它就无法正常工作。有没有办法避免这种情况并使其发挥作用?

JSFiddle: http://jsfiddle.net/dpjzJ/

改用visibility: hidden;或类似这样的类:

.hide {
   position: absolute !important;
   top: -9999px !important;
   left: -9999px !important;
}

或者这个(来自样板(:

.visuallyhidden { 
  position: absolute; 
  overflow: hidden; 
  clip: rect(0 0 0 0); 
  height: 1px; width: 1px; 
  margin: -1px; padding: 0; border: 0; 
}
您可能

知道,带有display: none;的内容在页面上没有位置。

查看有关该主题的这篇文章。

如果您

的目标是将scrollLeft和scrollTop设置为0(因为这是我的目标(,那么一个非常笨拙的解决方案是按照以下步骤操作:

  • 获取对要重置的元素的引用。
  • 获取对元素父级的引用。
  • 从父元素中删除元素。
  • 将元素追加回父元素。

scrollTop 和 scrollLeft 现在将设置回 0,即使它们是不可见的。

function resetScroll(element) {
    element.parentElement.replaceChild(element,element)
}

这会将 scrollTop 和 scrollLeft 设置为 0,即使不显示任何内容也是如此。

使用示例:

resetScroll(document.getElementById("my_scroll"))

这并不理想,但我解决这个问题的方法是添加一个一次性IntersectionObserver,该在元素第一次可见时触发。下面是一个函数,用于在元素首次可见时添加回调:

function onVisible(element, callback) {
  new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if(entry.intersectionRatio > 0) {
        callback(element);
        observer.disconnect();
      }
    });
  }).observe(element);
}

并像这样使用它:

let myElement = document.querySelector("#myElement");
// When the element first becomes visible, scroll it to 500px:
onVisible(myElement, el=>el.scrollTop=500);

示例:https://jsbin.com/gigumewemo/edit?html,output