简体   繁体   中英

How to avoid the mouseover event from the parent element when the mouse is exiting both parent and child if the parent has a border

Edit: What I want is for the nested div to not be moved when the mouse leaves both it and the parent div. I'm pretty sure it is currently moving because the border somehow extends the parent further out than the nested div. I'd like to keep the border.

Like someone once said, a demo is worth a 1000 words .

I have a div nested in a div

<div class='parent'>
    <div>Check me out</div>
</div>

That has some styling

.parent {
    width: 100%;
    border: 1px solid black;
}
.parent div {
    display: inline-block;
    position: relative
}

And some accompanying Javascript

var navBar = document.querySelector('div.parent');
var navItems = navBar.querySelector('div');
var moveNav = false;
var overItems = false;

navBar.addEventListener('mouseout', function() { moveNav = false; });
navItems.addEventListener('mouseover', function() { overItems = true; });
navItems.addEventListener('mouseout', function() { overItems = false; });
navBar.addEventListener('mouseover', function() { moveNav = !overItems && true; });
navBar.addEventListener('mousemove', moveToMouse);
function moveToMouse(e) {
    if(!moveNav)
        return;
    navItems.style.left = (e.offsetX - Math.floor((e.offsetX+navItems.offsetWidth)/navBar.offsetWidth) * (e.offsetX + navItems.offsetWidth - navBar.offsetWidth + 10)) + 'px'
}

The purpose is to keep some part of the child div under the mouse while the mouse is inside the .parent div.*

What I'd like to know is how to make the child div not be moved as the mouse exits the .parent div?

In other words, I want it to act like it does in this fiddle . The difference between the fiddles is that the first has a border around .parent and the second is borderless.

And of course, I've noticed that child div jerks around instead of moving smoothly. Suggestions as to how to avoid that are welcome but not expected.

*if there's some better way to accomplish that, please do point it out**

**don't say "use jQuery"

在带有边框的div的示例中,我使用mouseenter事件代替了mouseover事件,它似乎按照您想要的方式工作。

navBar.addEventListener('mouseenter', moveToMouse);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM