Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - How to detect textarea size change with pure javascript?

I want to notify when the size of textarea changes, what event happens at that time, how can I detect it?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Here is a small example using pure (without jQuery etc. dependencies) Javascript.

It's using mouseup and keyup handlers and an optional intervall to detect changes.

var detectResize = (function() {

  function detectResize(id, intervall, callback) {
    this.id = id;
    this.el = document.getElementById(this.id);
    this.callback = callback ||?function(){};

    if (this.el) {
      var self = this;
      this.width = this.el.clientWidth;
      this.height = this.el.clientHeight;

      this.el.addEventListener('mouseup', function() {
        self.detectResize();
      });

      this.el.addEventListener('keyup', function() {
        self.detectResize();
      });

      if(intervall) setInterval(function() {
          self.detectResize();
      }, intervall);

    }
    return null;
  }

  detectResize.prototype.detectResize = function() {
      if (this.width != this.el.clientWidth || this.height != this.el.clientHeight) {
        this.callback(this);
        this.width = this.el.clientWidth;
        this.height = this.el.clientHeight;
      }
  };

  return detectResize;

})();

Usage: new detectResize(element-id, intervall in ms or 0, callback function)

Example:

<textarea id="mytextarea"></textarea>
<script type="text/javascript">
var mytextarea = new detectResize('mytextarea', 500, function() {
  alert('changed');
});
</script>

See it in action on jsfiddle.net/pyaNS.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...