gpt4 book ai didi

javascript - 如果完全在 View 中(大于视口(viewport)),intersectionObserver 获得比率 1

转载 作者:行者123 更新时间:2023-12-03 07:11:09 25 4
gpt4 key购买 nike

我有一个页面分为多个部分。现在在滚动时,我尝试使用导航项底部边框的宽度来显示进度( View 中有多少部分)。在下面,您将找到我如何实现它的示例。

现在你可以看到,如果一个部分高于视口(viewport),intersectionRatio 将永远不会达到 1(这反过来不会绘制全宽边框)。我可以使用任何选项或替代方法来实际实现全宽度吗?

(function() {
var sections = [],
links = {},
thresholdSet = [[]],
observerOptions = {
root: null,
rootMargin: "0px",
threshold: _buildThresholdList()
};

function _init() {
if (!'IntersectionObserver' in window) {
return;
}

sections = document.getElementsByClassName('section');

for(var i = 0; i < sections.length; i++) {
var observer = new IntersectionObserver(_intersectionCallback, observerOptions),
section = sections[i],
link = document.getElementById('js-' + section.id);

links[section.id] = {
node: link,
initialWidth: link.offsetWidth
};

observer.observe(section);
}
}

function _buildThresholdList() {
for(var i = 0; i <= 1.0; i += 0.01) {
thresholdSet[0].push(i.toFixed(2));
}

console.table(thresholdSet[0]);
return thresholdSet[0];
}

function _intersectionCallback(entries) {
entries.forEach(function(entry) {
var section = entry.target;
var link = links[section.id];
var width = link.initialWidth * (entry.intersectionRatio || 0) + "px";

link.node.style.width = width;

console.log(section.id, entry.intersectionRatio);
});
}

_init();
}());
body {
display: flex;
}

.aside {
flex: 0 0 150px;
}

.nav {
position: sticky;
top: 0;
}

.nav li {
margin-bottom: 20px;
}

.nav li span {
display: inline-block;
padding-bottom: 10px;
border-bottom: 2px solid red;
}

.sections {
flex: 1;
}

#page1 {
height: 350px;
background-color: #cc8136;
}

#page2 {
height: 1500px;
background-color: #6538c4;
}

#page3 {
height: 1300px;
background-color: #9e7f9b;
}

#page4 {
height: 300px;
background-color: #568574;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="aside">
<ul class="nav">
<li><span id="js-page1">page1</span></li>
<li><span id="js-page2">page2</span></li>
<li><span id="js-page3">page3</span></li>
<li><span id="js-page4">page4</span></li>
</ul>
</div>
<div class="sections">
<div class="section" id="page1"></div>
<div class="section" id="page2"></div>
<div class="section" id="page3"></div>
<div class="section" id="page4"></div>
</div>
</body>
</html>

最佳答案

K 所以而不是使用 entry.intersectionRatio , 我正在使用 entry.intersectionRect.height / viewportHeight .

关于javascript - 如果完全在 View 中(大于视口(viewport)),intersectionObserver 获得比率 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59895216/

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