【问题标题】:Bold particular text in string on runtime jQuery运行时jQuery上的字符串中的粗体特定文本
【发布时间】:2022-02-07 18:23:43
【问题描述】:

我的要求是:这是一个输入字段。当用户要填写它时, 在运行时我搜索#tag 并使文本加粗。并希望将两组#tags分开

例如:“我更喜欢#FromSide #FromSide,想与更多的人交谈#ToSide强>" 第 1 组:#FromSide #FromSide 第 2 组:#ToSide

这是我的代码:

 `$('#custm-field').keyup(function(){`
            `let str = $(this).val();`
            `let arr = str.split(" ");`
            `$(arr).each((i,e)=>{`
                `if(e=="#")`
                `{ // $(e).css('font-weight','bold');`
                    `arr[i].replace(e,"<strong>"+e+"</strong>");}
                    `let newStr = arr.join(" ");`
            `$('#custm-field').val(newStr)`
            `});`

【问题讨论】:

  • 你能表达一下你在运行这段代码时遇到的问题吗?
  • Onn 运行这段代码,没有得到想要的输出

标签: php jquery


【解决方案1】:

这可以使用 RegEx 来实现:

$('#custm-field').keyup(function(){
  let str = $(this).val();
  str = str.replace(/#(.+?)\s/, '<strong>$1</strong>');
  $('#custm-field').val(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="custm-field"></input>

但是,粗体效果不会显示在输入字段中,您需要contenteditable element

【讨论】:

  • 特定代码返回输出:你好 ok 但在我的情况下,标签对用户不可见,而是标签的 innet 文本将是粗体
  • 你用的是什么类型的输入框?
  • 将我示例的输入元素更改为您的,看看它是否有效
  • 如果你已经在使用 contenteditables
【解决方案2】:

我已经为你构建了一个解决方案,

首先,您不能在输入标记的值内添加 HTML 标记。所以你必须使用contenteditable HTML 属性,通过在任何元素上将它设置为true contenteditable="true",你就可以开始编辑它的内容(写在里面)。

注意:我添加了背景颜色以使其在空白时可见

<div contentEditable="true" id="text" style="background-color: #eee;"></div>

您的 JavaScript (JQuery) 将如下所示:

请注意,您的代码有许多我必须修复的错误。

$('#text').keyup(function(){
            // get the div element
            let e = document.querySelector('#text');
            // get only the text inside the element (without the HTML tags)
            let str = e.innerText;
            e.innerHTML = '';
            // create a new element to contain our text because you cant add HTML text inside a DOM element directly
            let tag = document.createElement('div');
            let arr = str.split(" ");
            // this string will contain our HTML and text 
            let newStr = ``;
            $(arr).each((i,e)=>{
                if(e[0]=="#")
                { 
                    newStr += `<strong>${e}</strong>`;
                }
                else{
                    newStr += `${e}`
                }
                newStr += ` `;
            })
            // add the string to the inner HTML of the element we created
            tag.innerHTML = newStr;
            // append the newly created element inside the div
            e.append(tag);

            // based on Vito Gentile answer
            // this is to move the cursor to the end of the text we added, other wise the cursor would be at start of the text
            cursorManager.setEndOfContenteditable(e);
        });

我使用了this answer的代码,这就是cursorManager.setEndOfContenteditable(e);这行的来源。为方便起见,这是他们的代码。

(function( cursorManager ) {

            //From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
            var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];

            //From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
            Array.prototype.contains = function(obj) {
                var i = this.length;
                while (i--) {
                    if (this[i] === obj) {
                        return true;
                    }
                }
                return false;
            }

            //Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
            function canContainText(node) {
                if(node.nodeType == 1) { //is an element node
                    return !voidNodeTags.contains(node.nodeName);
                } else { //is not an element node
                    return false;
                }
            };

            function getLastChildElement(el){
                var lc = el.lastChild;
                while(lc && lc.nodeType != 1) {
                    if(lc.previousSibling)
                        lc = lc.previousSibling;
                    else
                        break;
                }
                return lc;
            }

            //Based on Nico Burns's answer
            cursorManager.setEndOfContenteditable = function(contentEditableElement)
            {

                while(getLastChildElement(contentEditableElement) &&
                    canContainText(getLastChildElement(contentEditableElement))) {
                    contentEditableElement = getLastChildElement(contentEditableElement);
                }

                var range,selection;
                if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
                {    
                    range = document.createRange();//Create a range (a range is a like the selection but invisible)
                    range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
                    range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                    selection = window.getSelection();//get the selection object (allows you to change selection)
                    selection.removeAllRanges();//remove any selections already made
                    selection.addRange(range);//make the range you have just created the visible selection
                }
                else if(document.selection)//IE 8 and lower
                { 
                    range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
                    range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
                    range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                    range.select();//Select the range (make it the visible selection
                }
            }

}( window.cursorManager = window.cursorManager || {}));

希望这能如你所愿。

【讨论】:

    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 2012-07-23
    • 2022-11-24
    • 2014-11-05
    • 2012-04-05
    相关资源
    最近更新 更多