[英]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>
由於h2
和p
是兄弟姐妹,但是您想在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.