[英]How to dynamically change contents of HTML page based on current window size
我有一個簡單的網頁,它是其他頁面的目錄。 我有五個圖像用作其他頁面的按鈕,但是我需要以特定的方式顯示它們。 我將所有內容居中放置,滾動時背景是靜態的並且不會移動,但是問題出在按鈕上。
我希望它們根據瀏覽器的當前高度具有特定的高度。 我之所以說當前高度,是因為如果用戶調整窗口大小,則需要調整自身高度 。
另外,更重要的是,我需要這樣做來防止目錄大於瀏覽器的高度。 我注意到在不同的屏幕分辨率下,圖像變大或變小,因此看起來可能很糟糕。
因此,例如,無論瀏覽器窗口有多大,我都希望瀏覽器底部和目錄之間,瀏覽器頂部與目錄之間的高度保持相同的空間是或用戶屏幕的分辨率。
我當時想通過javascript,使用諸如window.innerHeight
東西來獲取窗口的大小,並將包含目錄的div的高度設置為此值。
到目前為止,這是我所擁有的,但是腳本似乎根本不執行任何操作(這是我第一次使用javascript,因此我很可能會做一些愚蠢的事情。):
<html>
<head>
<style>
html, body {
height: 100%;
}
body {
background-image: url(../images/background.png);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
#logo {
width: 200px;
margin-top: 15px;
}
.c1 {
width: 300px;
margin-top: 15px; <!--margin between buttons-->
}
</style>
<title>Some Title</title>
</head>
<body bgproperties="fixed"> <!--static background-->
<div align="center" id="contents">
<div >
<a href="http://somewebpage">
<img id="logo" src="images/logo.png" alt="Logo"> <!--title button-->
</a>
</div>
<div >
<a href="http://somewebpage">
<img class="c1" src="images/img1" alt="image 1"> <!--second button-->
</a>
</div>
<div>
<img class="c1" src="images/img2" alt="image 2"> <!--third button-->
</div>
<div >
<img class="c1" src="images/img3" alt="image 3"> <!--fourth button-->
</div>
<div>
<img class="c1" src="images/img4" alt="image 4"> <!--fifth button-->
</div>
</div>
<script>
var ht = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight; <!--Get the height of the browser-->
document.getElementById("contents").style["height"] = ht; <--set height of table of contents-->
</script>
</body>
</html>
您可以通過CSS進行所有設置,但也可以使用JavaScript。
您需要在Percentage(%)中設置屬性; 如:
寬度:90% (您可以根據需要在屏幕上顯示替換值)
為了防止寬度不超過指定寬度,您可以設置最大寬度 (以百分比為單位)
您可以將height設置為auto 。
$(document).resize(function(){
if(document.innerHeight > 350) {
do something
}
});
我同意調整大小,寬度和高度等其他答案。但是在閱讀您的問題后,我認為響應式UI是您正在尋找的東西。 為什么不嘗試使用BootStrap這樣的框架來幫助您。 除了重新發明輪子之外,我們還可以使用一些非常容易使用的東西。 getbootstrap.com是該網址,易於實現。 (由於信譽不佳,我無法將其發布為評論:))
您可以通過兩種方式實現目標:
CSS Media Queries :CSS檢測視口的大小(窗口,因為缺少更好的解釋方法),並且如果視口與@media
查詢匹配,則應用某些規則。 以下是一些示例。 另外,請查看此CodePen ,以更好地了解其工作原理。
/* If the browser width is anything less than 100px, */ @media (max-width: 100px){ /* Set the height of an element */ #my_element{ height: 200px; } } /* If the browser width is 1000px or more, */ @media (min-width: 1000px){ /* Set the height of an element */ #my_element{ height: 2000px; } } /* You can also do widths in ranges. If the width is between 600px and 800px, */ @media (min-width: 600px) and (max-width: 800px){ /* Styles here */ } /* This applies to height as well */ @media (max-height: 500px){ /* Styles here */ }
完成此任務的另一種方法是使用百分比單位 :將按鈕的寬度設置為50%,然后調整瀏覽器窗口的大小。 他們現在應該很靈活。 嘗試百分比,直到滿意為止。 就個人而言,我更喜歡媒體查詢,因為它們可以提高准確性,但是請選擇! 希望這對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.