[英]Javascript // Set margin-top to be negative half of site height
[英]Setting margin-top to the height of the page with JavaScript
我正在嘗試使用JavaScript將div的邊距頂部設置為窗口的高度減去220px。 我希望此值在窗口更改大小時更改。
這是我目前擁有的:
HTML
<body onresize="heroHeight()" onload="heroHeight()">
<div class="heroImage"></div>
<div class="content">
<!-- page content -->
</div>
</body>
CSS
.content {
margin-top: 0;
width: 100%;
}
最后是我的JavaScript:
function heroHeight() {
var heroCurHeight = document.getElementsByClassName("content")[0];
heroCurHeight.style.marginTop = (window.outerHeight - 220);
}
知道我在做什么錯嗎?
謝謝!
當您可以在CSS中完成相同的操作時,使用JS似乎太復雜了(當然,我不知道您的用例)
.heroImage {
margin-top: calc(100vh - 220px);
}
CSS vh
是表示視口高度的百分比單位。 (當視口更改大小時自動更新)
CSS calc()
用於對多種單位類型進行數學運算。
編輯:
您確實需要注意性能,並且僅在用戶搞砸了窗口大小時才運行該功能。 這稱為“反跳”功能。 這是技術的很好概述 。
您必須指定單位
heroCurHeight.style.marginTop = (window.outerHeight - 220) + 'px';
您的問題出在這一行:
heroCurHeight.style.marginTop = (window.outerHeight - 220);
如果未與某些單位 (例如“ px”)一起設置,則無法設置頁margin-top
。 因此,您只需要將錯誤的行代碼更改為此:
heroCurHeight.style.marginTop = `${(window.outerHeight - 220)}px`
遵循完整的工作示例:
function heroHeight() { const heroCurHeight = document.getElementsByClassName("content")[0]; heroCurHeight.style.marginTop = `${(window.outerHeight - 220)}px` ; }
.content { margin-top: 0; width: 100%; height: 50px; background-color: red; }
<body onresize="heroHeight()" onload="heroHeight()"> <div class="heroImage"></div> <div class="content"> <!-- page content --> </div> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.