contenteditable 仿造input 光標定位

背景:在初次使用contenteditable寫可輸入的div模塊,當需求要求輸入限制字數,還要光標正常的狀況來模擬inputcss

直接上demo,用vue寫的(框架不重要),demo中用了vant的toast,css注意下是sassvue

若是你瞭解vue,能夠直接搭建一個demo項目,而後複製下下面的代碼運行起來就能看到效果
搭建demo能夠參考我以前的文章https://segmentfault.com/a/11...segmentfault

<template>
  <div class="edit-content-wrap">
    <div
      class="edit-content thin-scroll"
      contenteditable="true"
      ref="edit-content"
      placeholder="Ctrl+V 可粘貼文字"
      @keydown="inputChecked"
      @keyup="inputLength"
    >{{ comm_info }}</div>
    <div class="edit-footer">
      <div class="edit-footer-part-3">
        <span>{{ currentLength }}</span>
        /
        <span>10</span>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);
export default {
  name: 'Input',
  components: {},
  data() {
    return {
      comm_info: '',
      currentLength: 0
    };
  },
  mounted() {
  },
  methods: {
    inputChecked(e) {
      //Backspace鍵8 F5鍵116 37~40方向箭頭 Del鍵46
      if (
        e.target.innerText.length >= 10 &&
        e.keyCode !== 8 &&
        e.keyCode !== 116 &&
        e.keyCode !== 37 &&
        e.keyCode !== 38 &&
        e.keyCode !== 39 &&
        e.keyCode !== 40 &&
        e.keyCode !== 46
      ) {
        e.preventDefault();
      }
    },
    inputLength(e) {
      if (e.target.innerText.length > 10) {
        Toast.fail('最多可輸入10字');
        e.target.innerText = e.target.innerText.substring(0, 10);
        this.getInputSelection(e.target);
      }
      this.currentLength = e.target.innerText.length;
    },
    /**
     * 獲取輸入的光標到字符串最後一位
     * @param {obj} obj
     */
    getInputSelection(obj) {
      //處理光標問題
      if (window.getSelection) { //ie11 10 9 ff safari
        // obj.focus(); //解決ff不獲取焦點沒法定位問題
        let range = window.getSelection(); //建立range
        range.selectAllChildren(obj); //range 選擇obj下全部子內容
        range.collapseToEnd(); //光標移至最後
      } else if (document.selection) { //ie10 9 8 7 6 5
        let range = document.selection.createRange(); //建立選擇對象
        //var range = document.body.createTextRange();
        range.moveToElementText(obj); //range定位到obj
        range.collapse(false); //光標移至最後
        range.select();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.edit-content-wrap {
  width: 100%;
  border: 1px solid #dddddd;
  .edit-content {
    outline: none;
    min-height: 124px;
    width: 100%;
    text-align: justify;
    padding: 7px 10px;
    word-wrap: break-word;
    word-break: break-all;
    overflow-y: auto;
    &:empty::before {
      content: attr(placeholder);
      color: gray;
    }
  }
  .edit-footer {
    height: 36px;
    background: #f7f9fa;
    border-top: 1px solid #dddddd;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    .edit-footer-part-3 {
      .follow-small-height {
        width: 120px;
      }
    }
  }
}
</style>
相關文章
相關標籤/搜索