2013-12-11 133 views
1

這是一個簡單的網頁。爲什麼瀏覽器調整大小時textarea的寬度不會改變?JavaScript不影響HTML元素

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript"> 
    function resize() { 
     document.getElementById("main").style.width=window.innerWidth; 
    } 
    window.onresize = resize; 
    window.onload = resize; 
</script> 
</head> 
<body style="margin:0; padding:0;"> 
<textarea id="main" style="margin:0; padding:0; border:0;" >It was a dark and stormy night, and the rain came pouring down... </textarea> 
</body> 
</html> 
+3

@Phil op爲的onload運行它... ...這怎麼不是呢?如果只有我們可以減少評論。 – epascarello

+0

@epascarello oops。不建議閱讀脫機問題:) – Phil

+0

感謝大家的正確答案。這東西我有點生疏。 – WhiteHotLoveTiger

回答

2

style.width需要一個單元被設置,像px

document.getElementById("main").style.width=window.innerWidth + "px"; 
+0

當然!非常感謝。 – WhiteHotLoveTiger

+0

不客氣。 –

1

試試這個:

<!DOCTYPE html> 
<html> 
<head> 
</head> 
<body style="margin:0; padding:0;"> 
<textarea id="main" style="margin:0; padding:0; border:0;" >It was a dark and stormy night, and the rain came pouring down... </textarea> 
<script type="text/javascript"> 
    function resize() { 
     document.getElementById("main").style.width=window.innerWidth + 'px'; 
    } 
    window.onresize = resize; 
    window.onload = resize; 
</script> 
</body> 
</html> 
+0

這將如何解決這個問題? – Travesty3

+1

好吧,我收回了我的downvote,但爲什麼將腳本移動到textarea下面?正如問題下的評論所述,它在'window.onload'和'window.onresize'上運行。該元素在函數執行時存在。誠然,這不會傷害任何東西,但應該有理由暗示要這樣做。 – Travesty3

+0

@ Travesty3這是我的習慣,當我使用JavaScript來確保我的代碼將始終運行,即使不是'onload'。我認爲改變是很好的。 – HICURIN

1

替換您的線路以這樣的:

document.getElementById("main").style.width=window.innerWidth + 'px'; 
相關問題