我正在尝试使用一些 JAVASCRIPT 和 CSS 设置我的文本区域的样式,因此当单击它时,它应该通过 document.getElementById("tweet_area")
将大小从 20px 高度扩展到 120px 高度,但是当文本区域正在扩展时您只是在页面中单击而不是单击文本区域。有人能帮我了解一下这是 JavaScript 的新手吗
<script language="javascript">
document.onclick=changeElement;
function changeElement() {
var textarea = document.getElementById("tweet_area");
textarea.style.backgroundColor="#fff";
textarea.style.width="565px";
textarea.style.color="#000";
textarea.style.height="120px";
textarea.style.paddingLeft="1px";
textarea.style.paddingTop="1px";
textarea.style.fontFamily="Tahoma";
textarea.style.fontSize="10pt";
textarea.style.border="groove 1px #e5eaf1";
textarea.style.position="inherit";
textarea.style.textDecoration="none";
}
</script>
<style type="text/css">
#tweet_area{
width:565px;
height:25px;
overflow:hidden;
margin:1px auto;
font-family:Tahoma;
font-size:10pt;
font-weight:400px;
color:#000;
max-width:565px;
min-width:565px;
min-height:25px;
max-height:120px;
border:groove 1px #e5eaf1;
padding-right:10px;
}
</style>
最佳答案
您正在将点击处理程序应用于整个文档:
document.onclick=changeElement;
...所以这就是它响应页面上任意位置的点击的原因。尝试将它仅应用于文本区域:
document.getElementById("tweet_area").onclick=changeElement;
请注意,要让 document.getElementById()
找到您的元素,脚本必须在元素被解析后运行。因此,要么将脚本 block 放在元素之后(最好放在主体的末尾),要么将您的 JS 包装在 window.onload
处理程序中。
虽然你没有问,但我是否可以建议:不要在你的 JS 函数中设置所有这些单独的样式 - 相反,创建一个具有这些样式的类,然后将类添加到你的 JS 中。
关于javascript - 使用 Javascript 样式 onClick 展开文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16895256/