Javascript:如何更改图像源onclick [英] Javascript: how to change source of image onclick

查看:62
本文介绍了Javascript:如何更改图像源onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我身体里有10张图片,还有移动按钮。当我单击移动按钮时,我需要更改第一张和最后一张图像。我怎么能这样做?



我的尝试:



我试过这样的事情。



I have 10 images in the body, and Move button. When i click on Move button, i need to change first and last images. How can i do that?

What I have tried:

I have tried like this`

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Homework 6</title>
	<style>
		#btn1{
			width: 100px;
			height: 30px;
			margin: 50px 0 0 600px;
		}
		.d1{
			float: left;
			margin: 1px;
			width: 130px;
			height: 130px;
			background-size: cover;
		}
	</style>
</head>
<body>
	<div class="d1" style="background-image: url(Images/1.jpg)"></div>
	<div class="d1" style="background-image: url(Images/2.jpg)"></div>
	<div class="d1" style="background-image: url(Images/3.jpg)"></div>
	<div class="d1" style="background-image: url(Images/4.jpg)"></div>
	<div class="d1" style="background-image: url(Images/5.jpg)"></div>
	<div class="d1" style="background-image: url(Images/6.jpg)"></div>
	<div class="d1" style="background-image: url(Images/7.jpg)"></div>
	<div class="d1" style="background-image: url(Images/8.jpg)"></div>
	<div class="d1" style="background-image: url(Images/9.jpg)"></div>
	<div class="d1" style="background-image: url(Images/10.jpg)"></div>
	<button onclick="move()" id="btn1">Move</button>
</body>
<script src="JS/script.js"></script>
</html>













function move(){
	var arr = document.querySelectorAll(".d1")
	arr[0].style.background = url("../Images/10.jpg");
	arr[10].style.background = url("../Images/1.jpg");
}

推荐答案

以下是如何使用正确的语法更改图像的示例CP_js_changeImage - JSFiddle [ ^ ]



语法应为

Here is an example on how to change the image with the correct syntax CP_js_changeImage - JSFiddle[^]

The syntax should be
var arr = document.getElementsByClassName("d1");
arr[0].style.backgroundImage  = "url(path to image)";


这篇关于Javascript:如何更改图像源onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆