为什么我的JS函数不会在onresize事件上触发?

时间:2019-09-29 01:19:50

标签: javascript html centering event-listener onresize

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);

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

2 个答案:

答案 0 :(得分:1)

我相信您正在寻找"resize" event

这是更新的代码段(如果没有正确的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);

答案 1 :(得分:0)

我使用类似的功能来调整基于屏幕的动态svg图形。 我只是将onresize =“ function()”代码放置在标记中,并且它开箱即用。