日期:2014-05-16  浏览次数:20356 次

怎么样改变div中选中文本的颜色大小等属性
我需要做一个类似于百度贴吧发帖时候的输入框   百度贴吧的输入框是一个可编辑的div 这样可在里面显示插入的表情图片,但是还需要能够先选中div中的文字然后选择颜色,让其改变属性,请问下可以实现吗?
------解决方案--------------------
IE用document.selection对象,标准浏览器用window.getSelection,自己慢慢研究这2个东东

demo给个你参考

<style>
#editor{border:solid 1px #000;height:150px;width:300px;}
</style>
<div id="editor" contenteditable="true">测试内容</div>
<input type="button" value="红色" onclick="Color('red')" />
<script>
    function Color(c) {
        var e = document.getElementById('editor');
        e.focus();
        if (window.getSelection) {
            var s = window.getSelection(), r = s.getRangeAt(0);
            if (r.toString() == '') { alert('请选择内容!'); return }
            var sp = document.createElement('span');
            sp.style.color = c;
            r.surroundContents(sp);
            s.collapse(sp, 1);
        }
        else if (document.selection) {
            var r = document.selection.createRange();
            r.pasteHTML('<span style="color:' + c + '">' + r.text + '</span>');
        }
    }
</script>