将不同的样式应用于输入字段的最后x个字符

0 html javascript css input styling

到目前为止,我面临着一项任务,我不确定该如何完成。本质上,我有什么办法可以使字段的最后x个字符与其余字段显示不同?

假设这是对<input>字段的类型化输入,就会产生一些影响:“ TheLast6LettersOfThisShouldBe Bigger

那将是预期的效果。我可能想到的唯一可能的方法是使用两个单独的输入字段,并且第二个输入中的最后x个字符始终采用不同的样式。但是,这将给用户交互带来麻烦(第二个输入字段前面的退格将不会删除先前的字符)。

有什么想法或想法吗?

更新:我之前忘记提过,这是在用户键入时变成动态的事情。

Hug*_*rie 5

我相信您将无法使用经典的textarea,因为其中无法包含样式。我尝试了一个contenteditablediv。不涉及jQuery,可在您键入时实时运行。

const charLimit = 6; // replace by numbers of characters you want

const txt = document.getElementById('myInput');

txt.addEventListener('keyup', function(e) {
  const value = txt.textContent;
  const endString = value.length > charLimit ?
        value.substr(value.length - charLimit) : 
        value.substr(-value.length);
  const firstString = value.slice(0, -charLimit);

  txt.innerHTML = firstString + '<span>' + endString + '</span>';
  setEndOfContenteditable(txt);
});



// From https://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity/3866442#3866442
function setEndOfContenteditable(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
    }
}
Run Code Online (Sandbox Code Playgroud)
* {
  font-family: sans-serif;
}

#myInput {
  border: 1px solid #ccc;
  padding: 10px;
}

#myInput:focus {
  outline: none;
  border: 1px solid #333;
}

#myInput > span {
  font-weight: bold;
}
Run Code Online (Sandbox Code Playgroud)
<div id="myInput" contenteditable></div>
Run Code Online (Sandbox Code Playgroud)