html和js完成两张图片切换
时间: 2024-02-22 14:57:16 浏览: 25
可以使用HTML和JavaScript来实现两张图片的切换效果,具体代码如下:
HTML部分:
```html
<!DOCTYPE html>
<html>
<head>
<title>图片切换</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<img id="image" src="image1.jpg" alt="图片1">
</div>
<button onclick="changeImage()">切换图片</button>
<script src="script.js"></script>
</body>
</html>
```
JavaScript部分:
```javascript
var image = document.getElementById("image");
function changeImage() {
if (image.getAttribute("src") == "image1.jpg") {
image.setAttribute("src", "image2.jpg");
image.setAttribute("alt", "图片2");
} else {
image.setAttribute("src", "image1.jpg");
image.setAttribute("alt", "图片1");
}
}
```
以上代码中,我们使用了`<img>`标签来展示图片,并为其设置了一个id属性值为“image”。我们还在HTML中添加了一个按钮,点击按钮后调用`changeImage()`函数来进行图片切换。
在JavaScript中,我们通过`document.getElementById()`方法获取到了图片元素,并将其赋值给了一个变量`image`。在`changeImage()`函数中,我们通过`getAttribute()`方法获取到了图片的src属性值,如果为“image1.jpg”,则将其修改为“image2.jpg”,否则修改为“image1.jpg”,并通过`setAttribute()`方法来修改图片的src和alt属性值。
注意,以上代码中的图片文件需要根据实际情况进行修改,并且需要将JavaScript代码保存为一个名为“script.js”的文件,与HTML文件放在同一目录下。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)