向右滚动时检查

问题描述 投票:0回答:3

我希望能够检测用户是否使用

overlfow:scroll;
滚动浏览整个 div 不过 div 是水平的,所以使用
offset().top
在这里不起作用。
我目前有这个代码:

var elem = $('#slide');
var inner = $('#slidecontain');
if ( Math.abs(inner.offset().top) + elem.height() + elem.offset().top >= inner.outerHeight() ) {
  alert('bottom')
}

这非常适合检查我何时滚动到底部,但由于它是水平滚动,所以它会立即触发。我怎样才能切换这个?

offset().left
有可能吗?

这是 html,非常基本:

<div id="slide" style="width: 300px; height: 150px;">
        <div id="slidecontain" style="width: 900px; height: 150px;">
            <div class="slide1" style="width: 300px; height: 150px;"></div>
            <div class="slide2" style="width: 300px; height: 150px;"></div>
            <div class="slide3" style="width: 300px; height: 150px;"></div>
        </div>
<div>
jquery scroll offset horizontal-scrolling
3个回答
4
投票

可以使用 jQuery 轻松完成

.scrollLeft()

var elem = $('#slide');
var inner = $('#slidecontain');

elem.scroll(function() {
   if(elem.scrollLeft() + elem.width() == inner.width()) {
       alert("reached end!");
   }
});

这是一个模拟这个的小提琴


0
投票

jQuery 中有一个名为 .scrollLeft() 的方法可以在这里使用。但以相反的方式。

在寻找一些工作示例时,我发现了这个JSFiddle,由@Merianos Nikos

给出

如何运作?

HTML:

<div class="inner">
    <div id="long"></div>
</div>

JS:

jQuery(document).ready(function ($) {
    var lastLeftLocation = 0;
    $('.inner').scroll(

    function (e) {
        if (lastLeftLocation > $(this).scrollLeft()) {

        } else {
            console.log("moved to right");
        }
        lastLeftLocation = e.currentTarget.scrollLeft;
    });
});

这里是jsfiddle2

的简化版本

仅供参考:没有反向方法

.scrollRight()
;)

希望这有帮助。


0
投票

如果有人正在寻找基于 React 的解决方案,你可以尝试一下:

const containerRef = React.useRef<HTMLDivElement>(null);
const isScrolledRight = () => {
  if (containerRef.current) {
    const { current } = containerRef;
    return Math.abs(current.scrollWidth - current.clientWidth - current.scrollLeft) <= 1;
  }
  return false;
};

return(
  <div className='cardContainer' ref={containerRef}>
    <div className='card'><p>card text</p></div>
    <div className='card'><p>card text</p></div>
    <div className='card'><p>card text</p></div>
    <div className='card'><p>card text</p></div>
  </div>
)

CSS:

.cardContainer {
  flex-direction: row;
  width: 160px;
  display: flex;
  overflow-x: auto;
}
.card {
  width: 120px;
  height: 100px;
  flex: 0 0 auto;
}

Element.scrollLeft
是一个非四舍五入的数字,而
Element.scrollWidth
Element.clientWidth
是四舍五入的 - 因此确定滚动区域是否滚动到底部的唯一方法是查看滚动量是否足够接近某个阈值(即本例中为 1)。

参考:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

© www.soinside.com 2019 - 2024. All rights reserved.