【发布时间】:2020-08-06 23:38:29
【问题描述】:
我正在尝试使用 onmouseover 和 onmouseout 更改 h2 中的图像和文本,就像在这个 gif 中一样
我在下面给出了一些示例,我可以使用this 或document.getElementById 使用onmouseover 和onmouseout 更改图像,但是当我使用this 时,我无法弄清楚如何同时更改h2 标签内的文本(如document.getElementById 下的示例)。使用下面的 sn -p 不会改变图像。
onmouseover='(function(){
this.src="https://i.imgur.com/dsF2mgL.jpg"
document.getElementById("message").innerHTML="I am so very tired"
})()'
我正在寻找一种方法来使用 this 并更改 h2 中的图像和文本
使用document.getElementById
<h2>ICE 14: Drake the Duck</h2>
<img
id="duck"
src="https://i.imgur.com/G8TcUqA.jpg"
onmouseover='(function(){
//this.src="./duck2.jpg"
document.getElementById("duck").src="https://i.imgur.com/dsF2mgL.jpg"
document.getElementById("message").innerHTML="I am so very tired"
})()'
onmouseout='(function(){
document.getElementById("duck").src="https://i.imgur.com/PKi5s3p.jpg"
document.getElementById("message").innerHTML="Now I am wide awake!"
})()'
>
<h2 id="message">I am Drake the Duck.</h2>
使用this
<h2>ICE 14: Drake the Duck</h2>
<img
id="duck"
src="https://i.imgur.com/G8TcUqA.jpg"
onmouseover='this.src="https://i.imgur.com/dsF2mgL.jpg"'
onmouseout='this.src="https://i.imgur.com/PKi5s3p.jpg"'
>
<h2 id="message">I am Drake the Duck.</h2>
【问题讨论】:
-
你绝对不想要
getElementById。当浏览器引发事件时,它会向您传递一个事件对象,因此您也不需要this。function(event) { var img = event.target; var h2 = img.previousSibling;}。这种检索 H2 的方法的问题在于它是残酷的。如果您的标记结构发生更改,它将失败 -
@rayhatfield 在“使用
this”下的示例中
标签: javascript html onmouseover onmouseout