AddEventListener到当前目标

时间:2017-11-30 10:46:16

标签: javascript jquery

我正在尝试将一些鼠标移动添加到网格中元素内的背景图像中 -

这是我的HTML,它重复多次:

<div class="pure-u-1-3 grid-item" >
                            <div class="bg-img" style="background:url('images/blog/network.png'"></div>
                            <div class="blogInner" >
                                <p>SOME TEXT</p>
                                <a href="" class="lnk-a">Read More</a>
                            </div>

                        </div>

以下代码有效 - 但会移动所有元素 -

const bg = document.querySelector('.bg-img');
const bgIn = document.querySelector('.blogInner');
const windowWidth = window.innerWidth / 5;
const windowHeight = window.innerHeight / 5 ;

bgIn.addEventListener('mousemove', (e) => {
  const mouseX = e.clientX / windowWidth;
  const mouseY = e.clientY / windowHeight;

  bg.style.transform = `translate3d(-${mouseX}%, -${mouseY}%, 0)`;
});

我试图制作上面的代码rso,它只在hovered项目上运行,如下所示 -

 $('.grid-item').mouseover(function(event) {

const thisitem = $(event.currentTarget);
const bg = $(event.currentTarget).find('.bg-img');
const bgIn = $(event.currentTarget).find('.blogInner');


const windowWidth = window.innerWidth / 5;
const windowHeight = window.innerHeight / 5 ;

bgIn.addEventListener('mousemove', (e) => {
  const mouseX = e.clientX / windowWidth;
  const mouseY = e.clientY / windowHeight;

  bg.style.transform = `translate3d(-${mouseX}%, -${mouseY}%, 0)`;
});

});

在悬停时我收到错误: bgIn.removeEventListener不是函数 我完全被难倒了 - 因为悬停功能相同的代码正常工作 - 任何人都可以帮我理解什么是错的吗?

1 个答案:

答案 0 :(得分:1)

如果你只是使用jquery事件,它应该工作,而不是将本地js与jquery混合。

bgIn.mousemove((e) => {
  const mouseX = e.clientX / windowWidth;
  const mouseY = e.clientY / windowHeight;

  bg.css({transform: `translate3d(-${mouseX}%, -${mouseY}%, 0)`});
});