![](/img/trans.png)
[英]Whats the best way to convert an integer to a string in the context of making a "Loot" simulator?
[英]Trying to replace a string on the fly, whats the best way?
我試圖通過用跨距包圍它來動態替換一些文本。
例:
一個人在打字時,當他們鍵入單詞“ backwards”及其后面的空格時,會使整個句子或與該單詞對應的行加粗。
現在,我已經為其設置了CSS類,並且我一直試圖將其放到一個范圍內,但是我不確定它是否有效...它還會在發生新情況時重置,因此光標會跳回開頭它並不能讓我前進。
這是到目前為止我所擁有的(我的正則表達式現在也是錯誤的):
function replace(e) { if (e.keyCode == 13) { element = document.getElementById("script"); rg = /^INT/; element.innerHTML = element.innerHTML.replace( rg, '<span id="bold">$1</span>' ); }; };
<div contenteditable="true" id="script" style="width: 100%; height: 500px; border: 1px solid black;" onkeydown="replace(event)"> Replace </div>
如@Mouser所述,您的regEx將在開頭查找INT字符串。
這是正確的代碼。 您只需要根據需要修復RegEx。 我已經對其進行了測試。
function replace(e) {
if (e.keyCode == 13) {
element = document.getElementById("script");
var _str = element.innerHTML.trim("")
rg = /INT/;
element.innerHTML = _str.replace(
rg,
function($1) {
console.log($1)
return '<h1><span id="bold">' + $1 + '</span></h1>'
}
);
//Set cursor position
var range = document.createRange()
var _lastDom = element.childNodes[element.childNodes.length - 1];
var end = '';
if(_lastDom && _lastDom.innerHTML == undefined) {
end = _lastDom.length
} else {
_lastDom
end = 1
}
range.setStart(_lastDom,end)
range.setEnd(_lastDom,end)
sel = document.getSelection()
sel.removeAllRanges()
sel.addRange(range)
};
};
可能是一種更好的方法,但是這樣可能會有所幫助
var thepara=document.getElementById('thepara').innerHTML; document.getElementById('thetext').addEventListener('keyup',function(e){ var thetext=this.value; var thelength=this.value.length; var thestart=thepara.indexOf(thetext); var found=thepara.substr(thestart,thelength); if(found != "n" ){ var newstring="<span class='bolded'>"+found+"</span>"; document.getElementById('thepara').innerHTML=thepara.replace(found,newstring); } });
.bolded{font-weight:bold;}
<input type="text" id="thetext" /> <div id="thepara">It was a nice sunny day in the suburbs of South East London</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.