下面是我正在处理的项目中的简化代码示例。您能帮我理解和解决吗,为什么g div的背景在顶部是10px,而在左边是10px,就像p-1一样,里面的图像为什么会更高呢? >
因此,再次说明为什么背景要比640x480图像高,并且为什么还要向左扩展。请注意console.log语句,以帮助调试-应该没有“花哨的地方”,这意味着为什么所有内容都不只是在左/顶部开始/出现:10px,10px
var toggle = false;
function id(name) { return document.getElementById(name); }
function run() {
id('p-1').style.left = "10px"
id('p-1').style.top = "10px"
id('p-2').style.left = "660px"
id('p-2').style.top = "500px"
var w1 = id("p-1").clientWidth;
var h1 = id("p-1").clientHeight;
var l1 = id("p-1").style.left.replace("px", "");
var t1 = id("p-1").style.top.replace("px", "");
var w2 = id("p-2").clientWidth;
var h2 = id("p-2").clientHeight;
var l2 = id("p-2").style.left.replace("px", "");
var t2 = id("p-2").style.top.replace("px", "");
// "math" for the g size and position
var wOverlay = l2 - w1;
var hOverlay = t2 - h1;
var wg = w1 + w2 + wOverlay;
var hg = h1 + h2 + hOverlay;
var lg = ( l1 < l2 ) ? l1 : l2;
var tg = ( t1 < t2 ) ? t1 : t2;
console.log("p-1: (l,t)=(" +l1+ "," +t1+ "), (w, h) = (" +w1+ "," +h1+ ").");
console.log("p-2: (l,t)=(" +l2+ "," +t2+ "), (w, h) = (" +w2+ "," +h2+ ").");
console.log("g: (l,t)=(" +lg+ "," +tg+ "), (w, h) = (" +wg+ "," +hg+ ").");
id('g').style.left = lg + "px";
id('g').style.top = tg + "px";
id('g').style.width = wg + "px";
id('g').style.height = hg + "px";
console.log("div (l,t)=(" +id('g').style.left+ "," +id('g').style.top+ "), (width, height) = (" +id('g').style.width+ "," +id('g').style.height+ ").");
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.item {
position: absolute;
height: auto;
opacity: 1;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Div</title>
</head>
<body onload="run();">
<div class="item" id="g" style="background-color:gold;">
<img id="p-1" class="item" src="https://dummyimage.com/640x4:3/">
<img id="p-2" class="item" src="https://dummyimage.com/300/09f.png/fff">
</div>
</body>
</html>