将jQuery转换为Vanilla JS

时间:2020-05-27 23:43:52

标签: javascript jquery

我需要一些帮助将此jQuery转换为纯JavaScript,这是我必须转换的最后一个,以便可以从项目中完全删除jQuery。

function hoverFunc(e) {
  gsap.to(ball, {duration: 0.3, opacity: 1, scale: 0});
  gsap.to(ball, {duration: 0.3, scale: 0.5});
}

function unhoverFunc(e) {
  gsap.to(ball, {duration: 0.3, opacity: 1, scale: 1});
  gsap.to(ball, {duration: 0.3, scale: 1});
}

$("a").hover(hoverFunc, unhoverFunc);

3 个答案:

答案 0 :(得分:4)

您可以使用querySelectorAlladdEventListener将鼠标悬停/删除为

 var atags= document.querySelectorAll('a');

    atags.forEach(function(a) {
      a.addEventListener('mouseover', hoverFunc);
      a.addEventListener('mouseleave', unhoverFunc);
    })

答案 1 :(得分:1)

只是想用一个内联代码示例来说明Hien的示例,因此您可以运行下面的代码片段并查看其工作原理。在这里,我添加了3个链接,并且悬停功能向链接添加了2个单独的类,然后由取消悬停功能将其删除。

var atags= document.querySelectorAll('a');

function hoverFunc(e) {
  e.target.classList.add('hover', 'test')
}
function unhoverFunc(e) {
  e.target.classList.remove('hover', 'test')
}

atags.forEach(function(link) {
  link.addEventListener('mouseover', hoverFunc);
  link.addEventListener('mouseleave', unhoverFunc);
})
a {
  display: inline-block;
  padding: 1rem;
}
a.hover {
  background-color: rebeccapurple;
  color: white;
}
a.test {
  border: 3px solid black;
}
<a href="/">Link 1</a>
<a href="/">Link 2</a>
<a href="/">Link 3</a>

答案 2 :(得分:0)

类似的事情应该起作用

function hoverFunc(e) {
  gsap.to(ball, {duration: 0.3, opacity: 1, scale: 0});
  gsap.to(ball, {duration: 0.3, scale: 0.5});
}

function unhoverFunc(e) {
  gsap.to(ball, {duration: 0.3, opacity: 1, scale: 1});
  gsap.to(ball, {duration: 0.3, scale: 1});
}

var a = documet.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
  a[i].mouseover = hover;
  a[i].mouseout = unhover;
}