Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

jQuery - detect cut / paste with textarea auto-expand function

I have a function that auto-expands the textarea width and height however when I cut or paste the textarea value, the auto-expand function doesn't fire. How do I bind the resize function to detect when I paste in or cut away text?

$(document).ready(function() {
  var $inputs = $(".expandable");

  function resizeForText(text) {
    var $this = $(this);
    if (!text.trim()) {
      text = $this.attr("placeholder").trim();
    }
    var $span = $this.parent().find("span");
    $span.text(text);
    var $inputSize = $span.outerWidth(true);
    $this.css("width", $inputSize);
  }

  $inputs.find("textarea").keypress(function(e) {
    if (e.which && e.charCode) {
      var c = String.fromCharCode(e.keyCode | e.charCode);
      var $this = $(this);
      resizeForText.call($this, $this.val() + c);
    }
  });

  // Backspace event only fires for keyup
  $inputs.find("textarea").keyup(function(e) {
    if (e.keyCode === 8 || e.keyCode === 46) {
      resizeForText.call($(this), $(this).val());
    }
  });

  $inputs.find("textarea").each(function() {
    var $this = $(this);
    resizeForText.call($this, $this.val());
  });
  var textarea = $("textarea");
  textarea.on("input", function() {
    $(this).css("height", ""); //reset the height
    $(this).css("height", Math.min($(this).prop("scrollHeight")));
  });
});
textarea {
  resize: none;
  overflow: hidden;
  max-width: 200px;
  padding: .9rem;
  border: 1px solid #ededed;
  border-radius: 6px;
}

.expandable span {
  display: none;
  margin: 0 12px;
}

.measure {
  width: 200px;
  background: #ececec;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="measure">200px</div>
<div class="expandable">
  <textarea type="text" rows="1" class="textarea" placeholder="Placeholder" autocomplete="off"></textarea>
  <span></span>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...