基于按钮悬停的背景变化

问题描述 投票:0回答:1

我想根据悬停的按钮更改容器背景。 我想为容器中的另外两个或更多按钮做这个。但我找不到解决方案。谢谢你的帮助

我试过这个:

.mkdf-eh-item {
    background-image: url("base_img.jpg");
    background-size: cover;
    width: 100%;
    height: 300px;
}
.mkdf-eh-item { 
    pointer-events: none; 
} 
.mkdf-eh-item:hover { 
    background-image: url("hovered_img.jpg");
} 
.mkdf-eh-item .Button { 
    pointer-events: auto; 
} 
 .mkdf-eh-item .Button:hover { 
    background-color: transparent;
}
.mkdf-eh-item .Button1 { 
    pointer-events: auto; 
} 
.mkdf-eh-item .Button1:hover { 
    background-color: transparent;
}

但这仅适用于一个按钮。我希望每个按钮悬停时都有不同的图像

css wordpress
1个回答
0
投票

要根据悬停的按钮更改容器背景,可以结合使用 CSS 和 JavaScript。这是一个简单的方法:

document.querySelectorAll('.button').forEach(button => {
    button.addEventListener('mouseenter', function() {
        const newBg = this.getAttribute('data-bg');
        this.closest('.mkdf-eh-item').style.backgroundImage = `url(${newBg})`;
    });

    button.addEventListener('mouseleave', function() {
        this.closest('.mkdf-eh-item').style.backgroundImage = 'url(base_img.jpg)';
    });
});
.mkdf-eh-item {
    background-image: url("base_img.jpg");
    background-size: cover;
    width: 100%;
    height: 300px;
    transition: background-image 0.3s ease;
}

.button {
    pointer-events: auto;
    background-color: transparent;
    border: none;
    cursor: pointer;
}
<div class="mkdf-eh-item">
    <button class="button" data-bg="hovered_img1.jpg">Button 1</button>
    <button class="button" data-bg="hovered_img2.jpg">Button 2</button>
    <button class="button" data-bg="hovered_img3.jpg">Button 3</button>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.