gpt4 book ai didi

javascript - JS - 获取视口(viewport)中元素的百分比

转载 作者:数据小太阳 更新时间:2023-10-29 04:38:47 25 4
gpt4 key购买 nike

我想获取元素 (div) 在视口(viewport)中的百分比。

  • 当元素进入视口(viewport)时,我希望值为 0。
  • 当元素和元素的高度离开视口(viewport)时,我希望值为 100。

这是我想做的 5 个视口(viewport) http://imgur.com/2ZPpps5

我试过了:

$(window).bind('scroll',function(){
var viewportHeight = $(window).height(),
elementOffsetTop = $('#element').offset().top,
elementHeight = $('#element').height();

var numerator = 200 * (window.pageYOffset-elementOffsetTop+viewportHeight);
var denominator = (elementOffset+elementHeight+viewportHeight);
console.log(numerator/denominator);
});

此代码有效。 (我不明白为什么我必须乘以2)。

但是当我调整我的页面大小时,这段代码不起作用(值在 0 到 85 之间......)

想法?

最佳答案

更新:看起来这仍然有一点流量,所以这里有一个不使用 jQuery 的更新解决方案。

http://jsfiddle.net/nate/nmvka95j/20/

const element = document.getElementById("element");
const visible = document.getElementById("visible");

const logPercentageSeen = () => {
console.log(percentageSeen());
visible.textContent = `${percentageSeen()} %`;
};

window.addEventListener("scroll", logPercentageSeen);

const percentageSeen = () => {
// Get the relevant measurements and positions
const viewportHeight = window.innerHeight;
const scrollTop = window.scrollY;
const elementOffsetTop = element.offsetTop;
const elementHeight = element.offsetHeight;

// Calculate percentage of the element that's been seen
const distance = scrollTop + viewportHeight - elementOffsetTop;
const percentage = Math.round(
distance / ((viewportHeight + elementHeight) / 100)
);

// Restrict the range to between 0 and 100
return Math.min(100, Math.max(0, percentage));
};

// Log the initial value to the top before any scrolling has happened
logPercentageSeen();

这是旧的解决方案,ES6 之前的版本并使用我们亲爱的老 friend jQuery。

http://jsfiddle.net/nate/4N3Pj/1/

var $element = $('#element');
var $win = $(window);
var $vis = $('#visible');

$win.on('scroll', function () {
console.log(percentageSeen());
$vis.text(percentageSeen() + '%');
});

function percentageSeen () {
var viewportHeight = $(window).height(),
scrollTop = $win.scrollTop(),
elementOffsetTop = $element.offset().top,
elementHeight = $element.height();


if (elementOffsetTop > (scrollTop + viewportHeight)) {
return 0;
} else if ((elementOffsetTop + elementHeight) < scrollTop) {
return 100;
} else {
var distance = (scrollTop + viewportHeight) - elementOffsetTop;
var percentage = distance / ((viewportHeight + elementHeight) / 100);
percentage = Math.round(percentage);
return percentage;
}
}

$win.trigger('scroll');

关于javascript - JS - 获取视口(viewport)中元素的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20223243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com