需求
使用 Ctrl(+Alt) 可以将选中的字符或最后一个字符设置为上(下)标,支持数字、+、-、=、(、)。
代码
<template><div><el-input ref="elInput" v-model="objData[objDataProp]" size="mini"@keydown.ctrl.native="handleChange($event, 'up')"@keydown.ctrl.alt.native="handleChange($event,'down')"/></div>
</template><script>export default {name: 'widget-super-script',props: ['objData', 'objDataProp'],data() {return {}},methods: {charMapUp(v) {if (v === '0' || v === '₀') {return '⁰';}if (v === '1' || v === '₁') {return '¹';}if (v === '2' || v === '₂') {return '²';}if (v === '3' || v === '₃') {return '³';}if (v === '4' || v === '₄') {return '⁴';}if (v === '5' || v === '₅') {return '⁵';}if (v === '6' || v === '₆') {return '⁶';}if (v === '7' || v === '₇') {return '⁷';}if (v === '8' || v === '₈') {return '⁸';}if (v === '9' || v === '₉') {return '⁹';}if (v === '+' || v === '₊') {return '⁺';}if (v === '-' || v === '₋') {return '⁻';}if (v === '=' || v === '₌') {return '⁼';}if (v === '(' || v === '₍') {return '⁽';}if (v === ')' || v === '₎') {return '⁾';}},charMapDown(v) {if (v === '0' || v === '⁰') {return '₀';}if (v === '1' || v === '¹') {return '₁';}if (v === '2' || v === '²') {return '₂';}if (v === '3' || v === '³') {return '₃';}if (v === '4' || v === '⁴') {return '₄';}if (v === '5' || v === '⁵') {return '₅';}if (v === '6' || v === '⁶') {return '₆';}if (v === '7' || v === '⁷') {return '₇';}if (v === '8' || v === '⁸') {return '₈';}if (v === '9' || v === '⁹') {return '₉';}if (v === '+' || v === '⁺') {return '₊';}if (v === '-' || v === '⁻') {return '₋';}if (v === '=' || v === '⁼') {return '₌';}if (v === '(' || v === '⁽') {return '₍';}if (v === ')' || v === '⁾') {return '₎';}},handleChange(e, type) {let content = this.objData[this.objDataProp];if (!content) {//没有内容就不用进行后面操作return;}const start = e.target.selectionStart;//光标起始位置const end = e.target.selectionEnd;//光标结束位置if (end > start) {// 选中了字符for (let i = start; i < end; i++) {const vs = content.charAt(i);let vr = '';if (type === 'up') {vr = this.charMapUp(vs);} else if (type === 'down') {vr = this.charMapDown(vs);}if (vr) {content = content.substring(0, i) + vr + content.substring(i + 1);}}Vue.set(this.objData, this.objDataProp, content);const that = this;setTimeout(() => {const inputElement = that.$refs.elInput.$refs.input;if (inputElement) {inputElement.setSelectionRange(start, end);inputElement.focus();}}, 0);} else {// 最后一个字符let vp = content.substr(0, content.length - 1);// 前面几位let vs = content.substr(content.length - 1, 1);// 最后一位let vr = '';if (type === 'up') {vr = this.charMapUp(vs);} else if (type === 'down') {vr = this.charMapDown(vs);}if (vr) {Vue.set(this.objData, this.objDataProp, vp + vr);}}}}}
</script><style scoped></style>