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

问题描述 投票:-1回答:2

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

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

javascript html centering event-listener onresize
2个回答
1
投票

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

这里是更新的代码段(如果没有正确的HTML,它会出错,但会显示事件触发)。

"resize"

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.