我有以下CSS代码
#block {
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";
该图像当前显示在屏幕的左上角。为什么会这样呢?
最佳答案
#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