gpt4 book ai didi

javascript - 图像悬停生成器

转载 作者:行者123 更新时间:2023-12-03 00:48:28 26 4
gpt4 key购买 nike

假设我有以下 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.pngface2.pngface3.pngface4.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);
});
}

最佳答案

使用此 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);
});

关于javascript - 图像悬停生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com