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

How to replace a img element with a very similar gif element at its exact position at all times

在我的代码中,一个元素是在 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 始终在其确切位置替换图像?

尝试将变换原点 属性 添加到敌人 class 以将图像的原点设置为顶部而不是图像的中心。

.enemies{
 transform-origin: 0% 0%;
}

同样在css属性的爆炸id中设置。

html<img> 元素处缺少 style 属性,即 self-closing。在 left 属性 值处使用 calc() 设置 thewidth,在 .replaceWith() 调用处使用相同的值。

或者,使用 jQuery(),如@GeneParcellano 所建议,将相同元素的 srcid 属性替换为 .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/