1. 程式人生 > >onresize()調整瀏覽器視窗時,使圖片等控制元件自適應地變化大小

onresize()調整瀏覽器視窗時,使圖片等控制元件自適應地變化大小

今天學習JS時,按照教程裡如下程式碼實現“改變瀏覽器視窗的圖片自適應問題”,但沒有達到想要的效果,圖片在改變瀏覽器視窗的時候越變越大,重新整理頁面後又恢復原大小。

height = (document.body.clientHeight-100)*0.9;
document.getElementById("imageID").style.height = height.toString()+"px";

暫時還沒清楚為什麼以上程式碼無效,後來選用了onresize() 功能來實現自適應的功能,程式碼如下。僅通過 window.outerHeight 調整瀏覽器圖片的大小。
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%! int fontSize; %>
<!DOCTYPE html>
<html>
<head>
<title>testCSDN</title>

<script type="text/javascript">
	//setInterval("location.reload();",1000);
	function resizeCamera(){
		//alert('You have changed the size of the window');
		var height = (window.outerHeight-100)*0.3;
		//var width = (window.outerWidth-100)*0.3;
		document.getElementById("cameraImg1").style.height=height.toString()+"px";
		//document.getElementById("cameraImg1").style.width=width.toString()+"px";
	}
</script>

</head>
<body onresize="resizeCamera();" onload="resizeCamera();">
<p>
   當前日期: <%= (new java.util.Date()).toLocaleString()%>
</p>

<div style="margin-top:100px; text-align:center">
<img id="cameraImg1" src="/TomcatTest2/images/camera-normal.png" style="" onclick=""/><hr/>
<img id="cameraImg2" src="/TomcatTest2/images/camera-query.png"/></div>


</body>
</html>

效果圖如下:

(1)瀏覽器全屏時


(2)瀏覽器半屏時