【问题标题】:How to make link's background follows cursor?如何使链接的背景跟随光标?
【发布时间】:2021-09-27 02:05:31
【问题描述】:

我正在尝试制作动画链接。取决于从哪一侧光标进入链接 - 它的背景应该从下到上或从上到下出现。链接应该具有背景跟随光标的效果。

我设法让背景从下到上显示,但为什么反之不行?

Codepen

 <ul class="list">
  <li class="list__item">test link 1</li>
  <li class="list__item">test link 2</li>
  <li class="list__item">test link 3</li>
  <li class="list__item">test link 4</li>
  <li class="list__item">test link 5</li>
</ul>

.list__item {
  border: 1px solid red;
  display: flex;
  width: 300px;
  padding: 10px;
  cursor: pointer;
}

.from-top {
  transition: all .2s ease;
  background: linear-gradient(to bottom, red 50%, transparent 50%);
  background-position: top;
  background-size: 100% 200%;
}

.from-bottom {
  transition: all .2s ease;
  background: linear-gradient(to top, red 50%, transparent 50%);
  background-position: bottom;
  background-size: 100% 200%;
}


const list = document.querySelectorAll('.list__item');
list.forEach(item => {
   item.addEventListener('mouseover', (evt) => {
     if (evt.offsetY < 10) {
       console.log('top', evt.offsetY);
       item.classList.add('from-top');
     } else {
       console.log('bottom', evt.offsetY);
       item.classList.add('from-bottom');
     }
   });
  item.addEventListener('mouseleave', (evt) => {
    item.classList.remove('from-top');
    item.classList.remove('from-bottom');
  });
});

【问题讨论】:

    标签: javascript css animation hover gradient


    【解决方案1】:

    为了更好地理解这里发生了什么,我建议您弄清楚您实际尝试动画的属性。

    我稍微修改了您的笔以使其正常工作。 Here 你可以看到我的主要属性是background-size

    它在 from top 方向的示例中不起作用的原因是您为 background-sizebackground-position 设置动画,初始值为 top 并且您尝试从toptop - 这就是为什么在这种情况下什么都没有发生,反之亦然,从底部方向工作,因为动画从最初的 topbottom 你在 .from-bottom 中定义类。

    【讨论】:

    • 谢谢!这就是我需要的!:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    相关资源
    最近更新 更多