繁体   English   中英

如何将悬停效果添加到放置在父容器中的img

[英]How to add hover effect to img placed in parent container

使用CSS将鼠标悬停在链接Text后,如何为img添加悬停效果?

<div class="myTextContainer">
    <p>
        <a href="#">
            <img height="128" width="128" title="icon1" alt="icon1" src="icon1.png" ">
        </a>
    </p>
    <h2>
        <a href="#">Text</a>
    </h2>
</div>

更改您的HTML标记,然后将图标和文本都放入一个链接中。

<h2>
    <a>
        <img ...>
        TEXT
    </a>
</h2>

比您可以简单地使用

a:hover {color: red;} /* red text 'TEXT' */
a:hover img {border: 1px solid green}

尝试添加一些JavaScript。 以我为例,我添加了html属性onmouseover和onmouseleave来调用javascript函数。 将fun1悬停,将fun 2保留。 我在图像上添加了id悬停,并且在每个函数上都说要获取ID悬停的元素(即我的图像)并更改backgroundColor ='blue'。 在悬停时,我将其设置为蓝色,在离开时,将其设置为红色。 您可以通过执行style.src ='here / put / the / image / source / img.png'更改其他元素,例如src,并在悬停或离开时添加其他src。 如果您需要更多信息,请发表评论。 这有帮助吗?

 function fun1(){ document.getElementById("hover").style.backgroundColor='blue'; } function fun2(){ document.getElementById("hover").style.backgroundColor='red'; } 
 #hover{ background-color:red; } 
 <div class="myTextContainer"> <a href="#"> <img id="hover" height="128" width="128" title="icon1" alt="icon1" src="icon1.png"> </a> <h2> <a href="#" onmouseover="fun1()" onmouseleave="fun2()">Text</a> </h2> </div> 

--------或者通过不使用脚本标签或文件的方式进行--------

 #hover{ background-color:red; } 
 <div class="myTextContainer"> <p> <a href="#"> <img id="hover" height="128" width="128" title="icon1" alt="icon1" src="icon1.png"> </a> </p> <h2> <a href="#" onmouseover="document.getElementById('hover').style.backgroundColor='blue';" onmouseleave="document.getElementById('hover').style.backgroundColor='red';">Text</a> </h2> </div> 

由于h2p是兄弟姐妹,但是您想在p之前的h2 img上添加悬停,因此无法使用CSS来实现。 您需要javascript:

document.querySelectorAll('a')[1].addEventListener('mouseover', fn, false);
document.querySelectorAll('a')[1].addEventListener('mouseout', fn2, false);
function fn(e) {
 if(e.target.innerHTML == 'Text') {
  document.querySelector('img[src="icon1.png"]').className = 'hover';
 }
}
function fn2(e) {
 if(e.target.innerHTML == 'Text') {
  document.querySelector('img[src="icon.png"]').className = '';
 }
}

您可以声明:

.myTextContainer a:hover img {
// your CSS
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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