如何正确地使条形滑动动画?

时间:2018-03-19 18:24:16

标签: javascript html css

我有两个按钮,当用户点击它们时会加下划线。但是,我希望.underline能够被动画/水平滑动到正在点击的按钮上。

演示:https://jsfiddle.net/ds1wr736/11/

截至目前,.underline刚出现并在点击按钮时消失。如何设置动画以平滑滑动(x值更改)到所选按钮而不会出现黑客和JQuery?



// subscriptions, link
// playlist, link

function switchTab(tab) {
  if (tab === 1) {
    document.getElementById("tab2").classList.add("underline");
    document.getElementById("tab1").classList.remove("underline");
  }
  else if (tab === 2) {
    document.getElementById("tab1").classList.add("underline");
    document.getElementById("tab2").classList.remove("underline");
  }
}

.bar {
  background-color: gray;
  padding: 20px;
}

.underline {
  border-bottom: 5px solid red;
}

button {
  width: 100px;
  height: 50px;
  background-color: white;
}

button:focus {
  outline: none;
}




2 个答案:

答案 0 :(得分:2)

你去吧。只有编辑过的课程在这里:

.underline:after {
  border-bottom: 5px solid red;
  animation-name: slideIn;
  animation-duration: 1s;
  width: 100%;
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
}

@keyframes slideIn {
    from {width: 0;}
    to {width: 100%;}
}

button{
  position: relative;
  width: 100px;
  height: 50px;
  background-color: white;
}

我所做的是我在按钮上使用了抽象的after元素,并将其定位为它的相对按钮。并使用了css动画。

答案 1 :(得分:2)

我没有动画边框,而是创建了一个对点击事件做出反应的附加元素。这允许我们跟踪“下划线”的位置和缩放,并在单击按钮时在按钮之间设置动画。

可以修改此选项以使用mouseover代替click来接受悬停事件。

let buttons = document.querySelectorAll('button');

buttons.forEach(button => {
  button.addEventListener('mouseover', hoverboard); // Hover event
  //button.addEventListener('click', hoverboard);
});

function hoverboard(e) {

  const board = document.querySelector('.hoverboard');
  // - 1 due to the border of the button
  let width = this.offsetWidth - 1;
  const firstChild = document.querySelector('.bar button:first-child');
  const lastChild = document.querySelector('.bar button:last-child');
  // - 19 due to padding being 20px on the left and removing 1 for the button's border
  let left = this.offsetLeft - 19;

  board.style.cssText = 'transform: translateX(' + left + 'px); width: ' + width + 'px;';

}
.bar {
  position: relative;
  background-color: gray;
  padding: 20px;
}

.underline {
  border-bottom: 5px solid red;
}

button {
  width: 100px;
  height: 50px;
  background-color: white;
}

button:focus {
  outline: none;
}

.hoverboard {
  position: absolute;
  width: 100px;
  height: 3px;
  background: red;
  transition: transform .25s ease, width .25s ease;
}
<div class="bar">
  <button id='tab1'>Tab 1</button>
  <button id='tab2' style="width: 65px;">Tab 2</button>
  <button>Tab 3</button>
  <div class="hoverboard"></div>
</div>