如何在输入时连续将div中的文本加粗

我有一个待办事项应用程序,要求我添加更多功能,例如:添加一些用于粗体和斜体文本的按钮。在输入中,按下“粗体”按钮后,要输入的文本将变为粗体,而前一个文本(按下“粗体”按钮之前的文本)将保持常规状态。我知道无法将输入中的文本部分加粗,因此我用 div 模拟了输入:


const div = document.querySelector('div');


div.innerHTML = '';


const bold = document.getElementById('boldBtn');

const italic = document.getElementById('italicBtn')


bold.style.backgroundColor = 'white';


let previousText = '';

let boldString = '';


boldBtn.addEventListener('click', () => {

    boldBtn.classList.toggle('bold-selected');

    if (boldBtn.classList.contains('bold-selected')) {

        boldBtn.style.backgroundColor = "gray";

        previousText = div.innerHTML;

        console.log(previousText)

        div.addEventListener('keydown', boldText)

    }

    else {

        bold.style.backgroundColor = "white";

        div.removeEventListener('keydown', boldText);

    }

})


function boldText(e) {

    div.innerHTML = div.innerHTML.substr(1)

    console.log("Previous text: " + previousText);

    const NOT_ALLOWED = ['Backspace', 'Shift', 'Control', 'Alt'];

    if (!NOT_ALLOWED.includes(e.key)) {

        boldString += e.key;

        console.log("Bold text: " + boldString)

        console.log(previousText + boldString)

        div.innerHTML = previousText + "<strong>" + boldString + "</strong>"

    }

}

div {

    border: 1px solid black;

    width: 200px;

    height: 20px;

  }

  

.font-style {

    border: 1px solid blue

  }

<div contenteditable="true"></div>

<button id="boldBtn" class="font-style">Bold</button>

<button id="italicBtn" class="font-style">Italic</button>

尝试在 div 中写下“cool”之类的内容,然后按粗体按钮,然后键入一个字母。你会看到 div 得到了这个innerHTML:letter+cool+boldletter。并且光标设置在div内容的开头。请帮助我或至少给出一个提示来完成想要的行为!我已经花了3-4个小时了,我准备放弃了......

编辑:我想我没有说清楚:我不想使 div 的整个内容变为粗体,而只是其中的一部分/部分/部分。如果没有按下任何按钮,则要写入的文本应该是常规的,如果按下粗体按钮,则要写入的文本应该是粗体,与斜体按钮相同。也许如果同时选择粗体和斜体,则未来的文本应该是粗体和斜体。但这是另一个问题......我想要的一个例子是https://html-online.com/editor/。删除默认文本,只在左侧面板上写字,然后尝试使用上面的粗体、斜体按钮。左侧面板中将显示 HTML 生成的代码。我需要相同的功能...


叮当猫咪
浏览 67回答 2
2回答

泛舟湖上清波郎朗

为了在选择“粗体”时使文本变为粗体,请从当前选择范围中获取范围并在其中插入元素“strong”。&nbsp; let range=window.getSelection.getRangeAt(0);&nbsp; let elem=document.createElement('strong');&nbsp; elem.innerHTML='&#8203;'&nbsp; range.insertNode(elem);这将使文本变为粗体,同样也适用于斜体选项。现在,当您需要禁用它时,问题就出现了,因为我必须清除选择中的当前范围,并将范围设置为“div”的末尾,并插入新元素“span”(我将 span 用于普通文本)。同样我也处理过以下情况当粗体和斜体按下时(在这种情况下您需要存储以前的元素)当按下 Enter 时( div 正在被创建并产生问题,所以我必须设置 keydown 侦听器并使用 document.execCommand 不创建 div 而是创建 br)如果有人有兴趣更新我的解决方案以使其有效,欢迎您var boldButton=document.querySelector('#boldBtn'),&nbsp;italicButton=document.querySelector('#italicBtn'),contentDiv=document.querySelector('#content'),bold=false,italic=false,range,prevElement,selection;;contentDiv.addEventListener('keydown',function(e){&nbsp;if (e.keyCode === 13) {&nbsp; &nbsp; &nbsp; &nbsp;window.document.execCommand('insertLineBreak', false, null);&nbsp; &nbsp; &nbsp; &nbsp;range=window.getSelection().getRangeAt(0);&nbsp; &nbsp; &nbsp; &nbsp;range.collapse();&nbsp; &nbsp; &nbsp; &nbsp;prevElement=undefined;&nbsp; &nbsp; &nbsp; &nbsp;if(bold) addElement('strong');&nbsp; &nbsp; &nbsp; &nbsp;if(italic) addElement('i');&nbsp; &nbsp; &nbsp; &nbsp;e.preventDefault();&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; return true;});boldButton.addEventListener('click',function(){&nbsp; &nbsp; debugger&nbsp; &nbsp; bold=!bold;&nbsp; &nbsp; boldButton.classList.toggle('border-black');&nbsp; &nbsp; if(!bold)&nbsp; &nbsp; &nbsp; disable('bold');&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; addElement('strong');});italicButton.addEventListener('click',function(){&nbsp; &nbsp;debugger;&nbsp; &nbsp;italic=!italic;&nbsp; &nbsp;italicButton.classList.toggle('border-black');&nbsp; &nbsp;if(!italic)&nbsp; &nbsp; &nbsp; &nbsp;disable('italic');&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; addElement('i');});function addElement(element){&nbsp; if(!selection)selection=window.getSelection()&nbsp; range=selection.getRangeAt(0);&nbsp; let elem=document.createElement(element);&nbsp; elem.innerHTML='&#8203;'&nbsp; if(prevElement)&nbsp; &nbsp; range.selectNodeContents(prevElement);&nbsp; range.collapse();&nbsp; range.insertNode(elem);&nbsp; elem.focus();&nbsp; prevElement=elem;}function disable(elem){&nbsp;if(italic && bold) return;setRangeAtEnd();&nbsp;let element=document.createElement('span');&nbsp;if(italic)&nbsp; &nbsp;element=document.createElement('i');&nbsp;else if(bold)&nbsp; &nbsp;element=document.createElement('strong');&nbsp;element.innerHTML='&#8203;'&nbsp;range.insertNode(element);&nbsp;range.setStart(element,1);&nbsp;element.focus();}function setRangeAtEnd(){&nbsp;let childNodes=contentDiv.childNodes;&nbsp;range=document.createRange();&nbsp;range.setStartAfter(childNodes[childNodes.length-1]);&nbsp;prevElement=undefined;&nbsp;if(!selection)selection=window.getSelection();&nbsp;selection.removeAllRanges();&nbsp;selection.addRange(range);}#content{border:1px solid black;height:150px;}.border-black{border:2px dotted black;}<div id="content" contenteditable="true"></div><br><button id="boldBtn"&nbsp; class="font-style">Bold</button><button id="italicBtn"&nbsp; class="font-style">Italic</button>

月关宝盒

是的,有一个解决办法,因为你可以使用 jquery 来解决这个问题<script>$(document).ready(function () {&nbsp;$("#boldBtn").click( function() {&nbsp;$("your input id or class").keyup(function () {&nbsp;$("your input id or class").css("fontWeight", "bold");&nbsp; });&nbsp;});});</script>其中your input id or class提到如果您有班级,则将其写为.classname或如果您有 id 则写为#id。希望这可以帮助你。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5