如何找到图像的中心,并将另一个图像放置在其上面?

dan*_*ski 5 html javascript cordova

HTML:

<img src="img/image1.jpg" id = "image1" style="width: 100%;" allign = "center">
Run Code Online (Sandbox Code Playgroud)

JavaScript:

var image1 = document.getElementById("image1");
Run Code Online (Sandbox Code Playgroud)

我如何获得该给定图像的中心,然后将另一个具有绝对位置的图像放置在其死点之上?

小智 6

您可以getBoundingClientRect()在图像上找到它们的确切位置并使用这些值进行计算。此方法将考虑 CSS 大小以及滚动位置等。

第二个图像使用固定位置放置在下面,用于演示,但您可以使用父 div 设置为相对,并使用绝对等将图像放置在其中。

例子

function centerImages() {
  var image1 = document.getElementById("image1");
  var rect1 = image1.getBoundingClientRect();
  var cx = rect1.left + rect1.width * 0.5;    // find center of first image
  var cy = rect1.top + rect1.height * 0.5;

  var image2 = document.getElementById("image2");
  var rect2 = image2.getBoundingClientRect();
  var x = cx - rect2.width * 0.5;            // use center of first, subtract second
  var y = cy - rect2.height * 0.5;
  image2.style.cssText = "position:fixed;left:" + x + "px; top:" + y + "px";
}
window.onload = window.onresize = window.onscroll = centerImages;
Run Code Online (Sandbox Code Playgroud)
<img src="https://i.stack.imgur.com/UDTPI.gif" id="image1" style="width: 100%;">
<img src="https://i.stack.imgur.com/fk5Js.gif" id="image2">
Run Code Online (Sandbox Code Playgroud)