Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

利用contenteditable做一个vue属性的输入框 #18

Open
huangchucai opened this issue Jul 20, 2017 · 2 comments
Open

利用contenteditable做一个vue属性的输入框 #18

huangchucai opened this issue Jul 20, 2017 · 2 comments

Comments

@huangchucai
Copy link
Owner

利用contenteditable做一个vue属性的输入框

  1. contenteditable属性

    这是一个html5 新增的一个属性,可以让你的元素内容可以编辑

    <p contenteditable=true>这是一个可以编辑的段落</p>

    那如何获取这个可以编辑的段落呢?我们知道原生js中,找到相应的dom元素,然后我们可以通过innerText和innerHTML获取对应的文本,所以在编辑的段落中,我们可以使用dom.innerText来获取相应的编辑内容

  2. 实现placeholder

    当然我们不至限于想获取一个编辑的内容,我们还需要实现input和textarea等占位提示符。

    • 首先我们把placeholder添加到编辑内容中

      <div contenteditable=true placeholder="添加描述符">
        
      </div>
    • 通过css来控制点击显示和隐藏

      div[contenteditable]:empty:not(:focus):before {
        content: attr(placeholder);
        color: #aaa ;
      }
  3. 通过vue来实现双向绑定

    对于经常使用vue的人都知道,v-model的双向绑定,其实就是一个语法糖,然后这个语法糖还只能在input select textarea等表单控件中使用,因此我们想手写一个双向绑定

    input的双向绑定

    <input v-model="something">

    改变的双向绑定

    <input :value="something" @input="somthing=$event.target.value"

    参照上面的我们来实现div的可编辑和双向绑定

    html部分

    <div contenteditable="true" v-text="content" @input="handleInput">
      
    </div>

    js

    export default {
      data() {
        return {
          content: ''
        }
      },
      methods: {
        handleInput($event){
          this.content = $event.target.innerText;
          
          // 拓展 如果想要只需要前100位数据
          this.content = this.content.substring(0,100)
        }
      }
    }

    最终写的代码地址

@forever-z-133
Copy link

唔...innerText 不包含换行的呀

@huangchucai
Copy link
Owner Author

huangchucai commented Aug 16, 2017

其实还是有很多坑的,实际项目中手机端不兼容...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants