2013-12-11 136 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'; 
相关问题