背景图像的单击更改>>

问题描述 投票:0回答:2

我正在尝试通过单击(mouseclick)来更改背景图像(其中有4张)。

目前,同一张图像在屏幕上出现4次(每个角1个)。我只希望在整个屏幕上显示一个图像,而当我单击当前图像时,其他图像替换它;再次单击时,依此类推。我不确定目前我的代码有什么问题。

HTML !!!!

<!DOCTYPE html>
<html lang="fr" dir="ltr">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

  <title> CODE </title>
  <link rel="stylesheet" type="text/css" href="css/style.css"/>
  <script src="js/jquery.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <script src="js/sketch.js"></script>

</head>

<body>

<div id="body" class="imageOne"></div>

</body>

</html>

JS !!!!

var bodyObj,
  className,
  index;

bodyObj = document.getElementById('body');
index = 1;
className = [
  'imageOne',
  'imageTwo'
];

function updateIndex() {
  if (index === 0) {
    index = 1;
  } else {
    index = 0;
  }
}

bodyObj.onclick = function(e) {
  e.currentTarget.className = className[index];
  updateIndex();
}

CSS !!!!

html, body, #body {
    height: 100%;
    width: 100%;
}

#body.imageOne {
    background-image: url("img1.png");
}

#body.imageTwo {
    background-image: url("img2.png");
}

#body.imageTwo {
    background-image: url("img3.png");
}

#body.imageTwo {
    background-image: url("img4.png");
}

我正在尝试通过单击(mouseclick)来更改背景图像(其中有4张)。此刻,同一张图像在屏幕上出现4次(每个角1个)。我想要...

javascript html onclick addeventlistener mouseclick-event
2个回答
0
投票

与其为每个图像使用类,不如将它们存储在一个数组中,然后以编程方式对其进行更改,这是很好的。请在下面找到代码段。


0
投票

这里是另一种方式(像以前一样使用类):

© www.soinside.com 2019 - 2024. All rights reserved.