JQUERY:点击bug时增加Textarea高度

时间:2017-06-16 08:35:17

标签: javascript jquery html css

我有这个textarea,我想在点击时增加它的高度,我还在它上面添加了一个DIV:

<div id = "postbox_container">
   <textarea id = "post_textarea" rows = "1" cols = "7" name = "text_post" placeholder = "Post..." required/></textarea>
</div>

它的CSS:

box-sizing: border-box;
width: 97%;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
font-size: 2.7vh;
padding: 1vh;
border: 0px solid #dedede;
resize: none;

transition: all 0.5s ease;

最后我的jquery:

$(document).ready(function(){

    $('#postbox_container').on('click', function(){

      $('#post_textarea').height('20vh');


    });

  });

这样可行,但每次点击textarea时,都会增加一个新的高度 - 所以点击它的次数越多,它就越长越长。我的观点是,每当用户第一次点击DIV时,我想让textarea的高度变为固定20vh。有什么想法吗?感谢。

4 个答案:

答案 0 :(得分:4)

添加一项检查,表示只会在第一次点击时运行:

$(document).ready(function(){
    var clicked = false;
    $('#postbox_container').on('click', function(){

        if (!clicked) { 
          $('#post_textarea').height('20vh');
          clicked = true;
        }

    });

});

当页面加载时我们知道该框没有被点击,那么当我们点击它时,我们告诉浏览器已经发生这种情况并将其设置为true - 所以当我们再次点击时,浏览器会跳过请求更改高度。

将高度重新放在焦点上:

$( "#post_textarea" )
  .focusout(function() {
    $('#post_textarea').height('[set the height you want to return to]');
  })

答案 1 :(得分:1)

您可以使用一个功能进行绑定。 但我已经测试了你的代码,它对我来说很好。

这是链接

https://jsfiddle.net/Saiyam/x91ts87z/5/

$('#postbox_container').one('click', function(){
 $('#post_textarea').height('20vh');
});

这只会绑定一次。

答案 2 :(得分:0)

您可以在用户点击时添加更改为“true”的标记,下次检查该标记时,如果标记为“true”则不执行任何操作。

var firstTime = false;
$(document).ready(function(){
     $('#postbox_container').on('click', function(){
        if(!firstTime){
            firstTime = true;
            $('#post_textarea').height('20vh');
        }
     });

});

答案 3 :(得分:0)

在评论之后,如果你想让textarea在失焦时恢复它的大小,你可以做这样的事情。

我故意用一种稍微不同的方法来开发Web Develop Wolf(好的答案,+ 1),以显示另一种方法。

CSS:

#postbox_container {
  box-sizing: border-box;
  width: 97%;
  font-family: 'Open Sans', sans-serif;
  font-weight: 300;
  font-size: 2.7vh;
  padding: 1vh;
  border: 0px solid #dedede;
  resize: none;
  transition: all 0.5s ease;
}

#post_textarea.selected {
  height: 20vh;
}

JS:

$(document).ready(function() {

  $('#post_textarea').on('focus', function() {
    $('#post_textarea').addClass('selected');
  });

  $('#post_textarea').on('focusout', function() {
    $('#post_textarea').removeClass('selected');
  });

});

小提琴:https://jsfiddle.net/q25h394m/

相关问题