javascript 通过单击页面中的某处显示图像

ql3eal8s  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(133)

我想创建这样的网站:https://davidgomezmaestre.com/?nav=1
当你点击没有按钮的地方,你会看到一张图片,背景颜色也取决于图片。
我会创建我自己的网站与Squarespace,但我找不到如何做到这一点.请帮助我(:
我试着从示例网站中找到原始代码,但实际上编码不是我的工作,我不能这样做。

c6ubokkw

c6ubokkw1#

您可以通过以下方式实现此目的:

  • 为您的图像添加一个array
  • 创建具有click event的新元素,
  • 将来自所述阵列的图像插入到所述元素中。

然后对背景色执行相同的操作,生成array颜色并将<body> CSS更改为click event

var counter = 0;

var bgColor = [
  "#e8dff5", // color array for background-color
  "#fce1e4",
  "#fcf4dd",
  "#ddedea"
];

var imgArray = [
  "https://i.stack.imgur.com/GqweJ.png", //add URLs for your images here
  "https://i.stack.imgur.com/tFC7W.png",
  "https://i.stack.imgur.com/WjZch.png",
  "https://i.stack.imgur.com/7ALBl.png"
];

container.onclick = function(e) { //add images on click-event

  if (counter == bgColor.length) counter = 0; //loop background colors
  if (counter == imgArray.length) counter = 0; //loop images

  document.body.style.background = bgColor[counter]; //change background 

  var pic = document.createElement('img'); //create new element 
  pic.src = imgArray[counter]; //add URL for images
  pic.classList.add("image"); //add class name for images
  pic.style.position = 'absolute';
  pic.style.top = e.clientY + 'px'; //place images where you click
  pic.style.left = e.clientX + 'px';
  this.appendChild(pic);
  counter++;
}

reset = document.querySelector(".reset") //remove images on click-event
reset.addEventListener('click', function() {
  document.querySelectorAll('.image').forEach(function(x) {
    x.remove();
  })
})
#container {
  width: 100vw; /* makes whole page clickable, make smaller if need */
  height: 100vh;
}

.image {
  width: 100px;  /* style your images here */
  height:100px;
}

.reset { 
  position: fixed; /* click to remove images */
  bottom: 10px;
  right: 10px;
  z-index: 999999; /* ensure reset isn't hidden behind images */
  cursor: pointer; /* indicates element is clickable */
}
<div id="container"></div>

<div class="reset">REMOVE IMAGES</div>

相关问题