0
我想從百分比(數量%)的視口獲得元素的可見性。使用純javascript獲取在視口中的元素可見性百分比
以下是我厭倦的代碼,但缺少一些東西。
function calculateVisibilityForDiv(div$) {
var windowHeight = window.innerWidth ||
document.documentElement.clientWidth,
docScroll = window.scrollTop || document.body.scrollTop,
divPosition = div$.offsetTop,
divHeight = div$.offsetHeight || div$.clientHeight,
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll +
windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll +
windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100)/divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100)/divHeight;
}
return result;
}
}
var getOffset = function(elem) {
var box = { top: 0, left: 0 };
if(typeof elem.getBoundingClientRect !== "undefined") box =
elem.getBoundingClientRect();
return {
x: box.left + (window.pageXOffset || document.scrollLeft || 0) -
(document.clientLeft || 0),
y: box.top + (window.pageYOffset || document.scrollTop || 0) -
(document.clientTop || 0)
};
},
我想從文檔視口中獲取DOM元素可見性百分比。
你能提供小提琴? –
@yogendarji jsFiddle鏈接https://jsfiddle.net/q16c1m7s/ –
檢查更新後的答案。 –