javascript - 如何始终在其确切位置用非常相似的 gif 元素替换 img 元素

标签 javascript jquery html css gif

在我的代码中,一个元素在 body 的任何地方随机生成,当它被点击时,它被另一个 gif 元素替换。我先使用 offset() 获取图像的 top 和 left 值,然后使用 replaceWith() 将其替换为 gif,并使用 css() 指定 gif 的 left 和 top 值,如下所示:

function randomInt(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

var thewidth = randomInt(1,1000);

$("body").prepend( "<img src='red_dot.png' class='enemies' id='enemy' left:thewidth/2 + 'px'></img>");

var n = $("#enemy").offset();
    console.log(n.left);
    console.log(n.top);
    $("#enemy").click(function()
    {
      $("#enemy").replaceWith("<img src='explosion.gif' id = 'explosion'></img>");
      $("#explosion").css({"left" : n.left+'px', "top" : n.top + "px"});
.enemies
{
  position: fixed;
  transform: scale(0.01,0.01);
}

#explosion
{
  transform: scale(0.1,0.1);
  position: fixed;
}

如您所见,两个位置都是固定的。当我运行它时,img 和 gif 位于不同的位置,我将顶部和左侧的值记录到控制台以检查它们是否相同。为什么它们在不同的位置,我该如何使 gif 始终在其确切位置替换图像?

最佳答案

html不见了style <img> 处的属性元素,它是自闭合的。使用 calc()left要设置的属性值 thewidth , 在 .replaceWith() 处使用相同的值打电话。

或者,使用 jQuery() ,正如@GeneParcellano 所建议的那样替换 src , id.attr() 相同元素的属性, 链条 .removeClass()删除 "enemies" .className在元素上。

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

var thewidth = randomInt(1, 1000);

$("body")
.prepend(
  $("<img />", { 
    src :"http://lorempixel.com/50/50/cats",
    "class": "enemies",
    id:"enemy",
    css: {
      left: "calc(" + thewidth / 2 + "px)"
    }})
  );

$("#enemy").click(function() {
  $(this)
  .attr({
     "src": "http://lorempixel.com/50/50/nature"
  ,  "id": "explosion"
  })
  .removeClass("enemies");
});
.enemies {
  position: fixed;
  /*transform: scale(0.01, 0.01);*/
}
#explosion {
  /*transform: scale(0.1, 0.1);*/
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

jsfiddle https://jsfiddle.net/mL1y1qk5/3/

关于javascript - 如何始终在其确切位置用非常相似的 gif 元素替换 img 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41787574/

相关文章:

javascript - 在本地浏览器中运行简单的react js

javascript - Notepad++ 中更好的 Javascript 语法高亮显示

javascript - 为什么这个 Javascript 无法识别鼠标抬起?

Javascript 使用日期范围分割

javascript - 从 HTML 中的 JavaScript 函数获取信息。如何?

jquery - 内容出现在汉堡包导航之外

javascript - jQuery - 使用 fadeOut 而不破坏元素

javascript - 将 HTML 转换为 php 数组

javascript - 如何在手机上调整html页面的大小

html - 溢出: hidden doesn't work on :after and :before pseudo elements