调整大小

时间:2018-01-23 09:55:21

标签: javascript

我的导航链接有一个下划线滑块,可以使用getBoundingClientRect()根据点击的元素<li>获取特定的宽度和位置。这可以按预期工作,但在调整浏览器窗口大小时,我想更新下划线滑块的位置。

就像现在一样,我只抓住第一个<li>的宽度和位置。我需要和想要做的是定位当前具有下划线滑块的特定<li>并在调整大小时更新其宽度和位置,以便在使用右<li>元素调整大小时跟随滑块。 / p>

任何提示如何抓取当前活动的<li> ??

这是我在示例中的代码,我只在每次调整大小时抓取第一个<li>https://codepen.io/Shenden/pen/PELbOM

脚本如下所示:

const lists = document.querySelectorAll('.dropdown > li');
const slider = document.querySelector('.slider');


function handleEnter() {
// from current li
 const dropCoords = this.getBoundingClientRect();
  //get the current li's width and height
 //apply coords of li's to the slider-div elem
 slider.style.setProperty('opacity', '1');
 slider.style.setProperty('width', `${dropCoords.width}px`);
 slider.style.setProperty('transform', `translate(${dropCoords.left}px)`);

}

//for each li-elem clicked trigger handleEvent function
lists.forEach(listLink => listLink.addEventListener('click', handleEnter));

window.addEventListener('resize', function(){
  const elem = document.querySelector('.dropdown > li').getBoundingClientRect();

  slider.style.setProperty('transform', `translate(${elem.left}px)`);
  slider.style.setProperty('width', `${elem.width}px`);
});

1 个答案:

答案 0 :(得分:1)

您可以通过使用以下类标记它来跟踪哪个项应该处于活动状态:

const lists = document.querySelectorAll('.dropdown > li');
const slider = document.querySelector('.slider');


function handleEnter() {
 //remove active item indicator class if it is present
 document.querySelector(".activeItem").classList.remove("activeItem");
 //add the active item indicator class to the current item
 this.classList.add("activeItem");

 //perform the move code for the underline
 const dropCoords = this.getBoundingClientRect();
 //get the current li's width and height
 //apply coords of li's to the slider-div elem
 slider.style.setProperty('opacity', '1');
 slider.style.setProperty('width', `${dropCoords.width}px`);
 slider.style.setProperty('transform', `translate(${dropCoords.left}px)`);

}

//for each li-elem clicked trigger handleEvent function
lists.forEach(listLink => listLink.addEventListener('click', handleEnter));

window.addEventListener('resize', function(){
  //select the correct item using the activeItem indicator class
  const elem = document.querySelector('.dropdown > li.activeItem').getBoundingClientRect();

  slider.style.setProperty('transform', `translate(${elem.left}px)`);
  slider.style.setProperty('width', `${elem.width}px`);
});

CodePen fork:right here