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

时间:2015-05-28 08:02:39

标签: html css

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

<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>

4 个答案:

答案 0 :(得分:1)

更改HTML标记,并将图标和文本放在一个链接中。

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

比你可以简单地使用

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

答案 1 :(得分:1)

尝试添加一些JavaScript。在我的情况下,我添加了html属性onmouseover和onmouseleave来调用javascript函数。有趣的悬停和乐趣2 onleave。我添加了id悬停在我的图像上,我在每个函数上说要获取id hover的元素,这是我的图像并更改backgroundColor =&#39; blue&#39;。在悬停时我将其设置为蓝色并且onleave我将其设置为红色。您可以通过执行style.src =&#39; here / put / the / image / source / img.png&#39;来更改src等其他元素。并在悬停或离开时添加不同的src。如果您需要更多信息,请发表评论。这有帮助吗?

&#13;
&#13;
function fun1(){
  document.getElementById("hover").style.backgroundColor='blue';
}
function fun2(){
  document.getElementById("hover").style.backgroundColor='red';
}
&#13;
#hover{
background-color:red;
}
&#13;
<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>
&#13;
&#13;
&#13;

--------或者通过这样做而没有脚本标签或文件--------

&#13;
&#13;
#hover{
background-color:red;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

由于h2p是兄弟姐妹,但您希望在h2 img之前添加悬停在p之前,您无法使用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 = '';
 }
}

答案 3 :(得分:-1)

你可以声明:

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