首页 > 解决方案 > 有没有办法根据其在 div 中的位置将“活动”类添加到列表项?

问题描述

我有一个带有可点击列表项列表的固定高度 div。在 div 的中间,我有一条绝对定位线,用于表示选定的项目。现在,它只是一条静态线路。

有没有办法将活动类添加到列表项,因为它是由行“选择”的?

http://dev.chrislamdesign.com/shortwave/

标签: javascriptjqueryhtmlcss

解决方案


解决方案之一是使用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。假定这些updown按钮可以滚动列表,但我没有此功能,因为这不是重点——只需自己滚动即可。active这里的要点是,每次单击这些按钮之一时,橙色线下的元素都会获得类。因此,请使用此代码并根据需要对其进行编辑。

编辑:我向容器添加了一个滚动事件侦听#wrap-scroll-1器,因为我猜滚动事件发生在它上面。如果没有 - 你可以改变它。看看这个实际操作:JsBin

第 2 版:添加事件侦听器以在每次页面滚动时重新分配橙色线坐标,以及在页面加载时。看看这里的结果:JsBin


推荐阅读