将不可见的 div 元素放置在照片上(onclick)(repl.it)

元素放置的视觉效果

我正在尝试制作一个“抚摸狗游戏”,我想在他的头上放一个 div,当你单击该 DIV 时,它会触发一个 JS 函数将照片更改为 .gif,然后再回到这里,这是我的代码JS:

function pet_head(){

    var image = getElementById("image");

    image.src="DogPet.gif";

    setTimeout(function(){

      image.src="dog.jpeg";


    }, 1000//length of gif

   );


};


HTML:


<div class="main">

  <img id="image" src="dog.jpeg">

  <div class="click></div>

</div>

CSS:


img{

height:100%;

width100%;

position:absolute;

}


米脂
浏览 94回答 2
2回答

一只斗牛犬

如果您在图像中使用绝对值,它将始终位于其他所有内容之上。看看下面,看看这是否是您想要的。function pet_head(event) {&nbsp; /*var image = getElementById("image");&nbsp; image.src = "DogPet.gif";&nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; image.src = "dog.jpeg";&nbsp; }, 1000 //length of gif&nbsp; );*/&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; alert('changed');};document.getElementById('click').addEventListener('click', pet_head);img {&nbsp; height: 100%;&nbsp; width: 100%;}div {&nbsp; /* This will center the image horizontally */&nbsp; display: flex;&nbsp; justify-content: center;&nbsp; position: absolute;}div#click {&nbsp; color: green;&nbsp; border: 2px solid red;&nbsp; top: 14%;&nbsp; height: 45%;&nbsp; width: 300px;&nbsp; position: absolute;}<div class="main">&nbsp; <div id="click"></div>&nbsp; <img id="image" src="https://i.insider.com/5df126b679d7570ad2044f3e?width=1100&format=jpeg&auto=webp" /></div>

拉莫斯之舞

这是您的代码的工作版本。另请注意(除了删除代码拼写错误之外)我添加object-fit: cover到您的img,以便它在视口大小变化时保留纵横比。function pet_head() {&nbsp; &nbsp;// var image = document.getElementById("image");&nbsp; &nbsp;alert("petting the dog");&nbsp; &nbsp;/* image.src = "DogPet.gif";&nbsp; &nbsp;setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp;image.src = "dog.jpeg";&nbsp; &nbsp;&nbsp; &nbsp; &nbsp;}, 1000 //length of gif&nbsp; &nbsp;); */&nbsp;};&nbsp;&nbsp;document.querySelector(".click").addEventListener("click", pet_head);img {&nbsp; height: 100%;&nbsp; width: 100%;&nbsp; position: absolute;&nbsp; object-fit: cover;&nbsp;&nbsp;}.click {&nbsp; position: absolute;&nbsp; left: 49%;&nbsp; top: 22px;&nbsp; height: 13vh;&nbsp; width: 17vw;&nbsp; cursor: pointer;}/* Presentational styles */.click {&nbsp; background: yellow;&nbsp; opacity: .1;}html, body {&nbsp; margin: 0;}*, *::before, &::after {&nbsp;&nbsp; box-sizing: border-box;&nbsp;}<div class="main">&nbsp; <img id="image" src="https://i.stack.imgur.com/FthXz.jpg">&nbsp; <div class="click"></div></div>jsFiddle
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5