在我的代码中,一个元素在 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/