我有一个水平滚动条,你可以在这里看到...
http://codepen.io/anon/pen/rxxEQb
除了您可以无限期地向右滚动之外,它工作得很好。
为了限制右滚动(这样当没有更多元素时你不能继续向右滚动),我想检测最后一个按钮(id=lastButton)何时比链接更靠左向右滚动 (id=goRightLink)。
我已经将这两个控制台输出添加到代码笔中,因此您可以按照我所看到的进行操作...
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 进入和离开 View 而变化。
我想要做的就是在数字中建立某种模式,告诉我何时应该阻止任何进一步的滚动权限(即,当按钮 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 属性的变化而变化(这是我没有预料到的!)
最佳答案
尝试包含 if
条件以检查 .tagUlContainer
width
加上组合的 a
元素 width
加上 #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");
}
}
}
关于jquery - 了解视口(viewport)外元素的 getBoundingClientRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34482245/