使用Javascript样式onClick展开textarea

时间:2013-06-03 11:04:11

标签: javascript css3

我试图用一些JAVASCRIPT和CSS来设置我的textarea样式,所以点击它时应该将尺寸从20px高度扩展到120px高度document.getElementById("tweet_area")但是当你在页面中点击任何不点击时textarea正在扩展textarea。我可以收集一些关于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>

3 个答案:

答案 0 :(得分:2)

您正在将点击处理程序应用于整个文档:

 document.onclick=changeElement;

...这就是为什么它响应页面上任何地方的点击。尝试将它仅应用于textarea:

  document.getElementById("tweet_area").onclick=changeElement;

请注意,要document.getElementById()找到元素,脚本必须在解析元素后运行。所以要么在之后放置脚本块(在正文的末尾是一个好位置),要么将JS包装在window.onload处理程序中。

虽然你没有问,如果我建议:不要在你的JS函数中设置所有这些单独的样式 - 而是创建一个包含这些样式的类,只需在JS中添加该类。

答案 1 :(得分:0)

当用户在TextArea中按Enter Key时,我已为TextArea调整了jQuery代码。您可以将其更改为TextArea的点击事件。

以下是帖子:https://stackoverflow.com/a/14211554

答案 2 :(得分:0)

使用CSS来设置textarea的样式,这里不需要javascrcipt样式。在特定类的CSS下准备你的风格,当你需要时,你可以添加你的元素这个类及其属性。这是更清洁的解决方案。使用focusblur事件获取textarea元素。这是example

HTML

<textarea rows="4" cols="50" id="txtArea">

<textarea>

JS

$(document).ready(function() {

    $('#txtArea').on("focus", function(event) {

        if(!$('#txtArea').hasClass('customTextAreaClass')){

            $('#txtArea').addClass('customTextAreaClass');

        }
    });

    $('#txtArea').on("blur", function(event) {

        if($('#txtArea').hasClass('customTextAreaClass')){

            $('#txtArea').removeClass('customTextAreaClass');

        }
    });
});

CSS

.customTextAreaClass{
    background-color: #fff;
    width: 565px;
    color: #000;
    height: 120px;
    padding-left: 1px;
    padding-top: 1px;
    font-family: "Tahoma", Geneva, sans-serif;
    font-size: 10pt;
    border: groove 1px #e5eaf1;
    position: inherit;
    text-decoration: none;  
}