首页 > 解决方案 > 分配给父 div 的事件侦听器在按钮上停止

问题描述

我有一个要登录的按钮列表,并希望为它们分配一个事件侦听器以获得 p5.js 悬停效果。我想将它分配给包装器,但是在按钮之间切换时,它不会检测到悬停。

我也在使用 Vue.js v2.6.11

<div class="main">
    <div class="google hover">
        <button @click="loginWithProvider('google')">
            Login with Google
        </button>
    </div>
    <div class="twitter hover">
        <button @click="loginWithProvider('twitter')">
            Login with Twitter
        </button>
    </div>
    <div class="github hover">
        <button @click="loginWithProvider('github')">
            Login with GitHub
        </button>
    </div>
</div>

和事件监听器:

第一个版本

const main = document.querySelector('.main');
main.addEventListener('mouseenter', () => {
    isHovered = true;
});
main.addEventListener('mouseout', () => {
    isHovered = false;
});

第二版:

const buttons = document.querySelectorAll('.hover');

buttons.forEach(button => {
    button.addEventListener('mouseenter', () => {
        isHovered = true;
    });
});
buttons.forEach(button => {
    button.addEventListener('mouseout', () => {
        isHovered = false;
    });
});

两者都具有相同的效果。在输入上工作,但是一旦我停止将鼠标悬停在一个按钮上并转到另一个按钮上(留在父级div中,mouseout被触发并且没有再次输入其他按钮(除非我离开父级 div)

标签: javascripthtmlcssvue.jsvue-component

解决方案


事实证明,添加边距会触发mouseenter&mouseout事件。我刚刚添加了一个这样的间隔 div:

<div class="main">
    <div class="google hover">
        <button @click="loginWithProvider('google')">
            <i class="fab fa-google"></i>
            Login with Google
        </button>
    </div>
    <div class="spacer"></div>
    <div class="twitter hover">
        <button @click="loginWithProvider('twitter')">
            <i class="fab fa-twitter"></i>
            Login with Twitter
        </button>
    </div>
    <div class="spacer"></div>
    <div class="github hover">
        <button @click="loginWithProvider('github')">
            <i class="fab fa-github"></i>
            Login with GitHub
        </button>
    </div>
</div>

并编辑了我的 CSS:

// Removed
.button {
  margin-buttom: 10px;
}

// Added
.spacer {
  height: 10px;
}

推荐阅读