【问题标题】:Change page color and image with JS用JS改变页面颜色和图像
【发布时间】:2022-10-25 01:01:30
【问题描述】:

const element = document.querySelector("body")
element.addEventListener('click', changeBackground)

function changeBackground (){
    element.classList.toggle('active')
}

const newImg = document.getElementById("newImage")
newImg.addEventListener('click', changeImage)

function changeImage(){
   newImg.setAttribute('src', './public/SwitcherLight.svg')
}

当我单击图像时,它会更改图像和页面的背景颜色,但是当我单击返回时,只有背景颜色会恢复到以前的样子,我希望图像也会发生同样的情况,但我不能

【问题讨论】:

  • 所以设置body的类......
  • 这不是问题,我需要当我单击图像时它会发生变化,当我再次单击时它会恢复到以前的状态,并且没有发生这种情况,我可以使用页面颜色来做到这一点
  • 好吧,我回答了我们最初的问题。您的编辑将其更改为另一个问题,因此这当然不再是问题。您需要设置一个新的图像源。
  • 是的,我只是看到我后来问错了。对不起

标签: javascript html events


【解决方案1】:

image = document.querySelector("#image");
changed_img=false

image.addEventListener('click', function(){
  document.body.classList.toggle('blue');      
  if (changed_img) {
    image.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/640px-Image_created_with_a_mobile_phone.png";
    changed_img=false
  } else {
  image.src="https://i.insider.com/602ee9ced3ad27001837f2ac?width=700"
    changed_img=true
  }
})
.red {
  background-color: red;
}

.blue {
  background-color: blue;
}
<html>
<body class="red">
  <img height="200" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/640px-Image_created_with_a_mobile_phone.png" id="image">
</body>
</html>

希望这有帮助。

【讨论】:

    猜你喜欢
    • 2013-05-26
    • 2013-03-26
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2019-04-06
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多