温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

javascript怎么实现富文本框选中对齐

发布时间:2022-03-24 11:06:04 来源:亿速云 阅读:130 作者:iii 栏目:开发技术

本篇内容介绍了“javascript怎么实现富文本框选中对齐”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

    需求:

    一个可编辑(contenteditable=true)的div,对齐选中内容,左、中,右 ,其实质是:对选中的末梢节点,找到块属性的父元素,设置text-algin:center:

    MDN:text-align CSS属性定义行内内容(例如文字)如何相对它的块父元素对齐。text-align 并不控制块元素自己的对齐,只控制它的行内内容的对齐。

    分析需求:

    我们来分解一下这个需求的三个关键问题: ”选中部分“,”块元素“,"末梢元素"

    1如何获取选中的部分 *

    这里涉及到的Web API Document.getSelection().getRangeAt(0) 这里只处理一个选取的情况

    注意:光标所在位置,光标所在节点 视为选中区域

    2什么是块元素

    MDN:

    display:block

    这个值会生成一个块级元素盒子,同时在该元素之前和之后打断(换行)。简单来说就是,这个值会将该元素变成块级元素。

    除非特殊指定,诸如标题(<h2>等)和段落(<p>)默认情况下都是块级的盒子。

    用做链接的 <a> 元素、 <span>、 <em> 以及 <strong> 都是默认处于 inline 状态的。

    3末梢元素(没有子节点的元素)

    我们操作对齐,实质是操作盒模型中的内容的对齐方式,也就是对:图片,文字 等设置对齐样式,在这里我称其为末梢节点

    实现思路:

    1、获取选区内的所有末梢元素(递归)

    2、找到这些末梢元素的父块元素,设置其text-align:'left|center|right'

    代码实现:

    前端页面:一个div contenteditable="true";三个按钮:触发对齐(左,中,右)

    javascript怎么实现富文本框选中对齐

    javascript怎么实现富文本框选中对齐

    document.querySelector("#btn_alignl").addEventListener("click", () => { Align.call(this, 'left') })
    document.querySelector("#btn_alignc").addEventListener("click", () => { Align.call(this, 'center') })
    document.querySelector("#btn_alignr").addEventListener("click", () => { Align('right') })

    js 代码:

    1、一个公共的Align方法,参数为:left|center|right

    /**
         * 1 通过getBoundaryEndNodes获取所有末梢元素
         * 2 遍历末梢节点,通过getBlockParent获取每一个末梢节点的父级block元素
         * 3 设置endnode 的 blockparent.style.textAlign=left|center|right
         * @param alignStr left|center|right
         **/
        function Align(alignStr) {
            const rng = document.getSelection().getRangeAt(0)
            const commonAncestor = rng.commonAncestorContainer
            //获取开始节点,到结尾节点之间的所有末梢节点
            let getBoundaryEndNodes = function (pNode) {
                if (pNode == boundaries.start) { boundaries.isStart = true }
                if (pNode == boundaries.end) {
                    boundaries.isEnd = true
                    resultNodes.push(pNode)
                    console.log(pNode)
                }
                if (boundaries.isStart == true && boundaries.isEnd == false && pNode.hasChildNodes() == false) { resultNodes.push(pNode); console.log(pNode) }
    
                if (pNode.hasChildNodes() && boundaries.isEnd == false) {
                    pNode.childNodes.forEach(node => {
                        getBoundaryEndNodes(node)
                    });
                }
            }
            //获取所有末梢节点
            let getEndNodes = function (node, nodes=[]) {
                if (node.hasChildNodes()) {
                    node.childNodes.forEach(node => {
                        getEndNodes(node, nodes)
                    });
                } else {
                    nodes.push(node)
                }
                return nodes
            }
    
            const startBoundaryNode = getEndNodes(rng.startContainer)[0]
            const endBoundaryNode = getEndNodes(rng.endContainer).pop()
            let resultNodes = [] //存放开始节点,到结尾节点之间的所有末梢节点
            let boundaries = { start: startBoundaryNode, end: endBoundaryNode, isStart: false, isEnd: false }
            getBoundaryEndNodes.call(this, commonAncestor)
            //遍历所有末梢节点,找到其块父元素 设置对齐样式
            resultNodes.forEach(node => {
                const blockparent = getBlockParent(node)
                if (!!blockparent && blockparent.style.textAlign != alignStr) {
                    blockparent.style.textAlign = alignStr
                }
            })
        }

    getBlockParent的实现--获取选中末梢节点的块父节点的实现

    	let blockTags = ['p', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'div', 'body', 'td', 'th']
        // let inlineTags = ['img', 'font', 'b', 'strong', 'span', 'a']
        let blockTagSet = new Map()
        blockTags.forEach((v) => { blockTagSet.set(v, true) });
        const source = document.querySelector('div.source');
    
        function getBlockParent(ele) {
            let result = undefined
            if (ele === source) {
                console.log('已找到editor的根,并没有找父级block元素');
                result = undefined
            } else {
                switch (ele.nodeType) {
                    //element: 判断ele是否是块级元素,判断依据1 display:block 2 默认的块级元素
                    case 1: {
                        const disPro = ele.style.display;
                        if (disPro && disPro.toLowerCase().indexOf('block') > -1) {
                            result = ele;
                        } else if (blockTagSet.get(ele.tagName.toLowerCase())) { result = ele }
                        else { result = getBlockParent(ele.parentElement) }
                        break;
                    }
                    case 3: {//textNode
                        if (!!ele.nodeValue.trim())
                            result = getBlockParent(ele.parentElement)
                        else result = undefined
                        break;
                    }
                    default: {
                        break;
                    }
                } //end switch
            }//end if
            return result
        }

    “javascript怎么实现富文本框选中对齐”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI