2024年hover需求实现

67 阅读1分钟

1、需求描述

这个需求本质上就是在hover一张图片的时候,显示另外一张指定的图片

2、最初实现

一开始是用js的onMouseEnter和onMouseLeave事件来完成的

2.1、html结构

<div onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
    <img></img>
    <img></img>
</div>

2.2、js

 const handleMouseEnter = (e)=>{
        e.target.children[0].style.display = 'none'
        e.target.children[1].style.display = 'block'
        e.target.style.cursor = 'pointer'
    
    }

    const handleMouseLeave = (e)=>{
        console.log('移出',e.target.children);
        e.target.children[0].style.display = 'block'
        e.target.children[1].style.display = 'none'
    }

2.3、css

css的话就是将第一张图片显示,第二张图片隐藏,分别设置这两个img的display属性值就行了。

2.4、问题

因为鼠标移入移出的操作是比较频繁的,所以导致我们的这两个事件也是不断的频繁触发,导致bug出现。

3、最终方案

舍弃掉事件的方式,采用css的方法来实现

                            &:hover {
                                .img {
                                    display: none !important;
                                }

                                .hoverImg {
                                    display: block;
                                }

                                .ppp {
                                    display: block;
                                }
                            }