-1

function getCentralPosition() {

  // This script verticaly centers the heading you see on the main home page video //


  // First save the parent div that houses the heading element into a variable named parentDiv.
  var parentDiv = document.getElementById('home-section-1');

  // Now obtain the total height (including padding, borders etc) of this parentDiv
  var parentDivHeight = parentDiv.offsetHeight;

  // Save the child div element that houses the heading into a variable named childDiv
  var childDiv = document.getElementById('home-first-overlay');

  // Now obtain the total height (including padding, borders etc) of this childDiv
  var childDivHeight = childDiv.offsetHeight;

  // Calculate the height difference between the parentDiv and childDiv by subtracting their heights and storing them 
  // in a variable named heightDiff

  var heightDiff = parentDivHeight - childDivHeight;

  // Obtain the precise position required from the top of the parentDiv by dividing heightDiff by 2

  var pos_from_top = heightDiff / 2;

  // assign pos_from_top as the value for 'top' on childDiv using "px"

  childDiv.style.top = pos_from_top + "px";

}

window.addEventListener("onresize", getCentralPosition);

没有窗口调整大小事件监听器,我按原样使用代码 - 但想法是,当尝试调整浏览器窗口等大小时它也保持在中心。认为没有必要,我只是想实现这一点。关于我应该尝试什么的任何想法?

4

2 回答 2

1

我相信你正在寻找"resize"活动

这是更新的片段(没有正确的 HTML 会出错,但会显示事件触发)。

function getCentralPosition() {

  // This script verticaly centers the heading you see on the main home page video //


  // First save the parent div that houses the heading element into a variable named parentDiv.
  var parentDiv = document.getElementById('home-section-1');

  // Now obtain the total height (including padding, borders etc) of this parentDiv
  var parentDivHeight = parentDiv.offsetHeight;

  // Save the child div element that houses the heading into a variable named childDiv
  var childDiv = document.getElementById('home-first-overlay');

  // Now obtain the total height (including padding, borders etc) of this childDiv
  var childDivHeight = childDiv.offsetHeight;

  // Calculate the height difference between the parentDiv and childDiv by subtracting their heights and storing them 
  // in a variable named heightDiff

  var heightDiff = parentDivHeight - childDivHeight;

  // Obtain the precise position required from the top of the parentDiv by dividing heightDiff by 2

  var pos_from_top = heightDiff / 2;

  // assign pos_from_top as the value for 'top' on childDiv using "px"

  childDiv.style.top = pos_from_top + "px";

}

window.addEventListener("resize", getCentralPosition);

于 2019-09-29T01:22:51.167 回答
0

I use a similar function to adjust a dynamic svg graph based screen size. I just place the onresize="function()" code in the tag and it works out of the box.

于 2019-09-29T01:30:52.407 回答