假设我有以下HTML代码:
<!doctype html>
<html lang="en">
<head>
<title> Lab 6 - Task 1 </title>
<meta charset="utf-8">
<script src="imagechanger.js"></script>
<style>
div {
width: 50%;
margin: auto;
text-align: center;
font-family: sans-serif;
}
img { width: 300px; }
</style>
</head>
<body>
<div>
<h1> Fernandel Faces </h1>
<img src="face1.png" id="faces">
<p> Ask a question! </P>
<p> Move Mouse Over Fernandel for a Response </p>
</div>
</body>
</html>
,我有4个名为face1.png
,face2.png
,face3.png
和face4.png
的文件,我该如何编写Javascript,以便当鼠标悬停在初始图像上时间,它随机更改为4张图像之一?
答案:
window.onload=function(){
var images = ["face1.png", "face2.png", "face3.png", "face4.png"];
document.getElementById("faces").addEventListener("mouseover", function(event) {
var random = images[Math.floor(Math.random() * images.length)];
event.target.setAttribute("src", random);
});
}
答案 0 :(得分:1)
使用此JavaScript:
var images = ["face1.png", "face2.png", "face3.png", "face4.png"];
document.getElementById("faces").addEventListener("mouseover", function(event) {
var random = images[Math.floor(Math.random() * images.length)];
event.target.setAttribute("src", random);
});