[英]Change text and image on mouseclick/mouseover in Javascript
I figured out how to change image on mouseover through javascript. 我想出了如何通过javascript更改鼠标悬停时的图像。 But unable to figure how to add description below the image on mouseover/mouseclick on respective image. 但是无法找到如何在鼠标悬停/鼠标单击相应图像上的图像下方添加描述。 I'm not good at jQuery. 我不擅长jQuery。 Please help me in solving the problem in javascript only. 请仅在javascript中帮助我解决问题。
<html>
<head>
<style>
.imgStyle {
height: 100px;
width: 100px;
border: 3px solid grey;
}
</style>
</head>
<body>
<img src="img/img_01.jpg" id="mainImage" />
<div id="describ01" style="display:none">Description 01</div>
<div id="describ02" style="display:none">Description 02</div>
<div id="describ03" style="display:none">Description 03</div>
<div id="describ04" style="display:none">Description 04</div>
<br />
<div id="myDiv" onmouseover="changeImage(event)">
<img src="img/img_02.jpg" class="imgStyle" />
<img src="img/img_03.jpg" class="imgStyle" />
<img src="img/img_04.jpg" class="imgStyle" />
<img src="img/img_05.jpg" class="imgStyle" />
</div>
<script type="text/javascript">
function changeImage(event) {
event = event || window.event;
var targetElement = event.target || event.srcElement;
if(targetElement.tagName == "IMG") {
document.getElementById("mainImage").src = targetElement.getAttribute("src");
}
}
</script>
</body>
</html>
If you want to use javascript then the answer will be 如果您想使用javascript,那么答案将是
document.getElementById("description").innerHTML = 'Hello World';
and if you want to use JQuery then 如果您想使用JQuery
$("#description").html("Hello World");
Hopefully it will help you 希望它将对您有帮助
Give each of your images a data attribute: 给每个图像一个数据属性:
<img src="img/img_02.jpg" class="imgStyle" data-text='text goes here' />
Then use this on hover: 然后在悬停时使用它:
if(targetElement.tagName == "IMG") {
document.getElementById("mainImage").src = targetElement.getAttribute("src");
document.getElementById("description").innerHTML = this.getAttribute("data-text");
};
Now you only need one description div as before. 现在,您只需像以前一样需要一个description div。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.