0

我有一个水平滚动条,你可以在这里看到......

http://codepen.io/anon/pen/rxxEQb

除了您可以无限期地向右滚动之外,它的效果非常好。

为了限制向右滚动(这样当没有更多项目时你不能继续向右滚动),我想检测最后一个按钮(id=lastButton)何时比向右滚动的链接更靠左( id=goRightLink)。

我已将这两个控制台输出添加到 codepen,以便您可以按照我所看到的...

console.log("right of go-right-link: " + $("#goRightLink")[0].getBoundingClientRect().right);

console.log("right of lastButton: " + $("#lastButton")[0].getBoundingClientRect().right);

我无法理解这些数字 - 当我向右滚动到足够远以使最后一个按钮(按钮 30)可见时,我可以设置值“go-right-link: 1389, lastButton: 1313”(其中很棒),但是如果我向左滚动一点,使按钮 30 现在不在屏幕上,我可以设置值“go-right-link: 1246, lastButton: 1389”。然后更奇怪的是,我再次向左滚动并得到 lastButton 的负值(-549)。

与其在此处进一步痛苦地描述这一点,不如使用 codepen 中的控制台输出来查看数字在 Button 30 进出视图时如何变化可能更容易。

我要做的只是在数字中建立某种模式,告诉我何时应该阻止任何进一步的滚动权限(即当按钮 30 可见时)。

非常感谢任何想法!


- - - 编辑 - - - -

我找到了一个辅助解决方案(我没有将其作为答案发布,因为它没有回答与理解 getBoundingClientRect() 有关的问题)。我最终只是简单地将 ul 中的所有按钮相加(无论它是在屏幕上还是在屏幕外,都会给出宽度)......

var widthOfAllTagLis=0;
          $("#tagUl li button").each(
                                    function() {
                                      widthOfAllTagLis = widthOfAllTagLis + $(this).outerWidth(true); //passing true includes margins (as well as padding)
                                    });

然后在任何向右的转换之前添加此检查...

if ($("#tagUl").width() + 5 < widthOfAllTagLis) { //perform transition 
} else {
//don't perform transition because we can already see all the buttons
}

这只是因为 $("#tagUl").width() 的结果会随着 margin-left 属性的变化而变化(这是我没想到的!)

4

1 回答 1

0

尝试包含if条件以检查.tagUlContainer widthplus 组合a元素widthplus #tagUL margin-left(这将是一个增加的负值)是否大于0

var tags = $("#tagUl"),
  w = parseInt(tags.find("li").css("width")) * tags.find("li").length;

function scrollTags(direction) {
  console.log(w + (parseInt(tags.css("marginLeft"))) + 200
             , tags.parent().width());
    if (direction == "right") {
      if (w + (parseInt(tags.css("marginLeft"))) + 200 >
          tags.parent().width()) {
        tags.animate({
          marginLeft: "-=200"
        }, "fast");
      }

    } else {
      if (parseInt(tags.css('marginLeft')) < 0) {
        tags.animate({
          marginLeft: "+=200"
        }, "fast");
      }
    }
}

codepen http://codepen.io/anon/pen/NxRJqK

另请参阅如果元素在视口中 - 停止滚动动画

于 2015-12-27T16:57:06.383 回答