javascript - 有没有办法根据其在 div 中的位置将“活动”类添加到列表项?
问题描述
我有一个带有可点击列表项列表的固定高度 div。在 div 的中间,我有一条绝对定位线,用于表示选定的项目。现在,它只是一条静态线路。
有没有办法将活动类添加到列表项,因为它是由行“选择”的?
解决方案
解决方案之一是使用document.elementFromPoint(x, y)
方法。像这样的东西:
let lineCoords, lineTop, lineCenter;
// try to remove these two lines, leave just the scroll event listener
// document.getElementById('scrollUp1').addEventListener('click', setActive);
// document.getElementById('scrollDown1').addEventListener('click', setActive);
// 2nd edition: added these event listeners
window.addEventListener('scroll', getLineCoords);
window.addEventListener('load', getLineCoords);
// added this line
document.getElementById('wrap-scroll-1').addEventListener('scroll', setActive);
function setActive() {
const li = document.elementFromPoint(lineCenter, lineTop + lineCoords.height);
clearActive();
li.classList.add('active');
}
function clearActive() {
const ul = document.getElementById('ul-scroll-1');
const activeLi = ul.querySelector('li.active');
if (activeLi) {
activeLi.classList.remove('active');
}
}
// 2nd edition: added this function
function getLineCoords() {
lineCoords = document.querySelector('.orange-line').getBoundingClientRect();
lineTop = lineCoords.top;
lineCenter = lineCoords.left + (lineCoords.width / 2);
}
您可以在此处看到这一点:JsBin。假定这些up
和down
按钮可以滚动列表,但我没有此功能,因为这不是重点——只需自己滚动即可。active
这里的要点是,每次单击这些按钮之一时,橙色线下的元素都会获得类。因此,请使用此代码并根据需要对其进行编辑。
编辑:我向容器添加了一个滚动事件侦听#wrap-scroll-1
器,因为我猜滚动事件发生在它上面。如果没有 - 你可以改变它。看看这个实际操作:JsBin
第 2 版:添加事件侦听器以在每次页面滚动时重新分配橙色线坐标,以及在页面加载时。看看这里的结果:JsBin
推荐阅读
- drake - Drake - 如何在 LCM 中可视化框架
- elasticsearch - Filebeat:如何导出特定 pod 的日志
- r - 在R中的函数中获取参数名称而不是值
- google-sheets - 我正在尝试为我正在处理的电子表格构建一个两步存档工具,以跟踪库存问题
- smalltalk - 多网络服务器 ajax 回调与 Enter 上的刷新
- python - 具有多个数据集的 LSTM
- javascript - 底部导航栏正在浏览我的组件(react-native)
- python - 有没有办法检查 ssm send_command 是否正常运行?
- android - 如何将最近的孩子添加到 Firebase 的顶部?
- c++ - 在末尾插入循环双向链表