如何在更改图像鼠标悬停事件中添加淡入淡出

How do I add a fade to a change image mouseover event?

本文关键字:事件 添加 淡入 淡出 悬停 鼠标 图像      更新时间:2023-09-26

到目前为止,这是我的Javascript函数:

function changeImg (){
    document.getElementById('main').style.backgroundImage = "url('./img/map/maphv.png')"
}
function changeBack () {
    document.getElementById('main').style.backgroundImage = "url('./img/map/map.png')"
}

这是在HTML:中

<div id="main"> 
    <a data-title="Africa" href="collection/africa.html" onmouseover="mouseoversound.playclip();changeImg()" onmouseout="changeBack()"><img class="africa" src="./img/map/africa.png" height="50"/> </a>

这是CSS:

#main {
 background-image: url(../img/map/map.png);
 background-size: 100%;
 background-repeat: no-repeat;
 width: 100%;
 height: 580px;
 position: relative;
 }
#main img.africa {
 top: 244px;
 left: 397px;
 height: 33.5%;
 position: absolute;
 width: 18%;
 opacity:0;
 }

#main img.africa:hover {
 top: 244px;
 left: 397px;
 height: 33.5%;
 position: absolute;
 width: 18%;
 opacity:1;
 transition: opacity .5s ease-in-out;
   -moz-transition: opacity .5s ease-in-out;
   -webkit-transition: opacity .5s ease-in-out;
 }

所以CSS是无关紧要的,但我发布了它,这样你就可以看到顶部悬停是如何逐渐消失的。我只是想将onmouseover事件的淡入添加到背景图主元素中。

所以我真的只需要在Javascript函数中添加fade,并将该函数添加到mouseover事件处理程序中吗?

任何像Javascript这样的想法都不是我的第一语言..;)

如果你可以使用jquery,那么你可以做一些类似的事情

FIDDLE演示

$("#main").on("mouseenter", function () {
    $(".africa").stop(true, true).fadeOut(); /***fadeIn or fadeOut***/
});

放弃Javascript

如果我正确理解你的问题,当你悬停在一个元素上时,你想在图像之间淡出,对吧?这可以很容易地在纯CSS中完成。

  • 指定要设置背景图像动画的元素
  • 添加与父元素大小相同的子元素。这可以是<img>,也可以是带有背景图像的span或div
  • 将子元素的不透明度设置为0,除非有人将光标悬停在父元素上

HTML

<div class="fading-bg">
    <img src="foo/bar.jpg" alt="stuff">
</div>

CSS

.fading-bg{
    position:relative;
    width: 100px;
    height: 100px;
    background: no-repeat center;
    background-size: cover;
}
.fading-bg img{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    opacity: 0;
    -webkit-transition: opacity 500ms;
    transition: opacity 500ms;
}
.fading-bg:hover img{
    opacity: 1;
}

Javascript非常棒,但在我个人看来,你应该避免将其用于像这样的简单动画,因为CSS完全可以自己完成。