簡體   English   中英

為什么我的 JS function 不會觸發 onresize 事件?

[英]why doesn't my JS function fire on the onresize event?

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

沒有 window 調整事件監聽器的大小,我按原樣使用代碼 - 但想法是,當嘗試調整瀏覽器 window 等大小時,它也會停留在中心。認為沒有必要,我只是想實現這一點。 關於我應該嘗試什么的任何想法?

我相信您正在尋找"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);

我使用類似的 function 來調整基於動態 svg 圖形的屏幕尺寸。 我只是將 onresize="function()" 代碼放在標簽中,它開箱即用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM