javascript - Translating .one and .on events from JQuery to JavaScript
问题描述
I found this piece of code to manage the he¡ght from textareas:
// Applied globally on all textareas with the "autoExpand" class
$(document)
.one('focus.autoExpand', 'textarea.autoExpand', function(){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.autoExpand', 'textarea.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0, rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
});
It comes from this link: https://codepen.io/vsync/pen/frudD
I would like to translate these lines to the JavaScript version.
Any help? Thanks in advance!
解决方案
remove .autoExpand
from focus.autoExpand
or input.autoExpand
because it's not valid event and try this.
document.querySelectorAll('textarea.autoExpand').forEach(function(item) {
// .one
item.addEventListener('focus', function(e) {
console.log('called once')
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
// remove event after called once
item.removeEventListener(e.type, arguments.callee);
// e.type is current event or "focus"
// arguments.callee is current callback function
})
// .on
item.addEventListener('input', function(e) {
var minRows = this.getAttribute('data-min-rows') | 0, rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
})
})
推荐阅读
- vba - 使用 VBA 更改 Power Query 中的 SQL 查询
- c - 如何在 C 中将类型为 AA:BB:CC:DD:EE:FF 的字符串转换为 0xaabbccddeeff?
- node.js - NodeJS/Passport 总是出现内部服务器错误(BattleNet 策略)
- python - 这个正则表达式发生了什么?
- ruby-on-rails - Ruby on Rails - 将用户数据导出到 csv - 按钮
- asp.net-mvc - 如何使用基于域的路由?
- sql - 升级 SonarQube 和 MS SQL Server
- javascript - 我可以在 javascript 函数中返回 2 种不同的数据类型吗
- mysql - 字段“外键”没有默认值
- c++ - 获取 C++ 中类实例的名称?