HTML -- Element元素滚动

Published: · LastMod: July 13, 2022 · 227 words

判断元素是否可以滚动 🔗

通过设置元素的scrollTop后再查看是否变化 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function eleCanScroll(ele) {
  if (!ele instanceof HTMLElement) {
    console.log("fuck off");
    return;
  }
  if (ele.scrollTop > 0) {
    return true;
  } else {
    ele.scrollTop++;
    // 元素不能滚动的话,scrollTop 设置不会生效,还会置为 0
    const top = ele.scrollTop;
    // 重置滚动位置
    top && (ele.scrollTop = 0);
    return top > 0;
  }
}

元素通过scrollHeight判断 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const isScrollable = function (ele) {
    // Compare the height to see if the element has scrollable content
    const hasScrollableContent = ele.scrollHeight > ele.clientHeight;
 
    // It's not enough because the element's `overflow-y` style can be set as
    // * `hidden`
    // * `hidden !important`
    // In those cases, the scrollbar isn't shown
    const overflowYStyle = window.getComputedStyle(ele).overflowY;
    const isOverflowHidden = overflowYStyle.indexOf('hidden') !== -1;
 
    return hasScrollableContent && !isOverflowHidden;
};