ehs*_*net 5 html javascript textarea
我想在textarea的大小发生变化时发出通知,当时发生了什么事,我该如何检测呢?
这是一个使用纯Javascript(无jQuery等依赖项)的小示例。
它使用mouseup和keyup处理程序以及可选的intervall来检测更改。
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;
})();
Run Code Online (Sandbox Code Playgroud)
用法: new detectResize(element-id, intervall in ms or 0, callback function)
例:
<textarea id="mytextarea"></textarea>
<script type="text/javascript">
var mytextarea = new detectResize('mytextarea', 500, function() {
alert('changed');
});
</script>
Run Code Online (Sandbox Code Playgroud)
可以在jsfiddle.net/pyaNS上看到它。
小智 -4
试试这个演示。
jQuery(document).ready(function(){
var $textareas = jQuery('textarea');
// set init (default) state
$textareas.data('x', $textareas.outerWidth());
$textareas.data('y', $textareas.outerHeight());
$textareas.mouseup(function(){
var $this = jQuery(this);
if ( $this.outerWidth() != $this.data('x')
|| $this.outerHeight() != $this.data('y') )
{
alert( $this.outerWidth() + ' - ' + $this.data('x') + '\n'
+ $this.outerHeight() + ' - ' + $this.data('y')
);
}
// set new height/width
$this.data('x', $this.outerWidth());
$this.data('y', $this.outerHeight());
});
});
Run Code Online (Sandbox Code Playgroud)
无法用纯 JavaScript 实现,我们必须使用jQuery