Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the alignment of rich text boxes with javascript

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to achieve rich text box alignment in javascript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Demand:

An editable (contenteditable=true) div that aligns the selection, left, center, and right. Its essence is: for the selected tip node, find the parent element of the block attribute and set the text-algin:center:

The MDN:text-align CSS attribute defines how the inline content, such as text, is aligned relative to its block parent element. Text-align does not control the alignment of the block element itself, only the alignment of its inline contents.

Analyze requirements:

Let's break down the three key issues of this requirement: "selected parts", "block elements", and "tip elements".

1 how to get the selected part *

The Web API Document.getSelection (). GetRangeAt (0) involved here deals with only one selected case

Note: the location of the cursor, the node where the cursor is located is regarded as the selected area

2 what is a block element

MDN:

Display:block

This value generates a block-level element box with breaks (line breaks) before and after the element. Simply put, this value turns the element into a block-level element.

Unless specifically specified, such as headings (etc.) and paragraphs (

) are block-level boxes by default.

The elements used as links, and are all in the inline state by default.

3 stub elements (elements without child nodes)

We operate alignment, which is essentially the alignment of the contents of the operation box model, that is, setting the alignment style for pictures, text, etc., which I call the tip node here.

The idea of realization is:

1. Get all the tip elements in the selection (recursion)

2. Find the parent block element of these tip elements, and set its text-align:'left | center | right'

Code implementation:

Front page: a div contenteditable= "true"; three buttons: trigger alignment (left, center, right)

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 Code:

1. A common Align method. The parameter is: left | center | right

/ * 1 get all the terminal elements through getBoundaryEndNodes * 2 iterate through the terminal node, get the parent block element of each terminal node through getBlockParent * 3 set the blockparent.style.textAlign=left of endnode | center | right * @ param alignStr left | center | right * * / function Align (alignStr) {const rng = document.getSelection (). GetRangeAt (0) const commonAncestor = rng.commonAncestorContainer / / get the start node All end nodes 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)}) }} / / get all the tip nodes 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 = [] / / store the start node All end nodes let boundaries = {start: startBoundaryNode, end: endBoundaryNode, isStart: false, isEnd: false} getBoundaryEndNodes.call (this, commonAncestor) / / traverses all end nodes Find its block parent element setting alignment style resultNodes.forEach (node = > {const blockparent = getBlockParent (node) if (!! blockparent & & blockparent.style.textAlign! = alignStr) {blockparent.style.textAlign = alignStr})}

The implementation of getBlockParent-- the implementation of getting the block parent node of the selected terminal node

Let blockTags = ['img',' font', 'baked,' 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 (' the root of editor has been found, not the parent block element') Result = undefined} else {switch (ele.nodeType) {/ / element: determine whether ele is a block-level element, based on 1 display:block 2 default block-level element 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} "how to achieve rich text box alignment in javascript" is introduced here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report