當前正在學習JavaScript,無法得到我的頭,或爲什麼它不工作。使用基於視口尺寸的javascript變量來改變CSS屬性
我正在嘗試使用基於視口尺寸的javascript變量來調整div的大小(因此div會專門針對手機的尺寸進行擴展或縮小,或者當您從橫向切換爲縱向時)。
目前,在Chrome檢查器中,它顯示0 0(左上角)的div,尺寸爲0px x 0px。 console.log確實提供了視口的尺寸,並建議它顯示爲縱向還是橫向。另外,我可以確認圖像在我設置的目錄中(因爲有一次我有這個工作,但後來我打破了背景,背景當前正在工作)。
這裏的JavaScript迄今爲止 -
$(document).ready(function() { //Variables for viewport height and width. var windowWidth = $(window).width(); var windowHeight = $(window).height(); //resizeCloud function alters cloud image size by append cloud ID to include H & W variables function resizeCloud() { $('#cloud').css('width: ',windowWidth + 'px'); $('#cloud').css('height: ',windowHeight + 'px'); $(window).resize(resizeCloud); }; //Will advise if app is in portrait or landscape console.log("width: " + windowWidth); console.log("height: " + windowHeight); if (windowWidth < windowHeight) { console.log("Portrait mode"); } else { console.log("Landscape mode"); };
});
而CSS -
#cloud { background-image: url('images/cloud.png'); position: absolute; top: 0; left: 0; background-size: contain;
的HTML只是< DIV ID = '雲'> </DIV>(沒有空格)。
如果有更簡單的方法來做到這一點,讓我知道!任何幫助非常感謝!
是的:(:(我會編輯我的主帖) – quitepenne
要清楚,你希望你的圖像大小爲100%,基於你的視口大小的權利,不確定問這樣的問題,只是創建了這個https:// jsfiddle。 net/2n255t6v /。如果不需要爲此編寫任何不需要的JS,則使用css本身處理它。 –