H5 contenteditable 属性学习

文章参考
http://www.zhangxinxu.com/wordpress/2016/01/contenteditable-plaintext-only/
http://www.w3school.com.cn/html5/att_global_contenteditable.asp

作为多行文本域功能来讲,textarea满足了我们大部分的需求。然而,textarea有一个不足就是不能像普通div标签一样高度可以跟随内容自适应

利用全浏览器都支持的 contenteditable 模拟文本域可以实现体验相当不错的高度跟随内容自动撑开的效果

我们设置可以设定一个最大高度(max-height),然后设置overflow: scroll; 就可以限定高度了

<div style="" class="border_000000 max_height_100px overflow_scroll" contenteditable="true" onchange="getUserInput()" onblur="blurAction()" id="contenteditableWidget" >
    <img src="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png" alt="到百度首页" title="到百度首页">
    <div class="color_3eb034">dsafdsaf</div>
</div>

<button onclick="getUserInput()">
    获取DIV中手动添加的内容
</button>

<script type="text/javascript">
    // 获取contenteditable里面的内容,是一个HTML代码
    function getUserInput(){
        var contenteditableWidgetObj = document.getElementById("contenteditableWidget");
        console.log(contenteditableWidgetObj.innerHTML);
//        console.log("innerText" + contenteditableWidgetObj.innerText);
//        console.log("textContent" + contenteditableWidgetObj.textContent);
    }

    // contenteditable 支持onblur事件
    function blurAction(){
        console.log("blurAction");
    }
    $(function(){

    });
</script>


备注:

1、设置了 contenteditable 属性之后,并不支持onchange事件

2、我是基于chrome 浏览器做的测试,并没有测试其他浏览器(公司的产品基于chrome内核,移动终端也是)

猜你喜欢

转载自hbiao68.iteye.com/blog/2366737