gpt4 book ai didi

javascript - 使用 createElement Javascript 制作的定位图像

转载 作者:行者123 更新时间:2023-11-28 07:52:20 25 4
gpt4 key购买 nike

我有以下 CSS 代码

#block {
width: 1000px;
height: 500px;
overflow: hidden;
background-image: url("images/back.png");
cursor: pointer;
}

我正在尝试创建一个位于 block 中间的图像。

var imag = document.createElement("IMG");
imag.setAttribute("src", "images/player_blue.png");
block.appendChild(imag);
imag.style.left = block.clientWidth/2 + "px";
imag.style.top = block.clientHeight/2 + "px";

图像当前显示在屏幕的左上角。为什么会这样?

最佳答案

需要设置position作为absolute

#block {
position: relative;
width: 1000px;
height: 500px;
overflow: hidden;
background-image: url("images/back.png");
cursor: pointer;
}

然后

var imag = document.createElement("IMG");
imag.setAttribute("src", "images/player_blue.png");
block.appendChild(imag);
imag.style.left = block.clientWidth / 2 + "px";
imag.style.top = block.clientHeight / 2 + "px";
imag.style.position = 'absolute';

演示:Fiddle

关于javascript - 使用 createElement Javascript 制作的定位图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30320931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com