쉬운 해결책은 요소의 innerHTML
속성을 span
에있는 단어를 감싸는 새 html 문자열로 바꾸는 것입니다. 그러나 매우 유연한 솔루션이 아니기 때문에 innerHTML
속성을 바꾸면 텍스트 노드 만 포함하는 요소를 대상으로하지 않는 한 모든 요소가 갱신되고 예기치 않은 결과가 발생할 수 있습니다.
this is some text and I want to replace the word cool
당신은 할 수 : :
var $body = $(document.body);
$body.html($body.html().replace(/\b(cool)\b/g, '<span style="color: red;">$1</span>'));
여기
, 모든 멋진 단어를 일치 그들에 캡처 그룹을 만들 것입니다 /\b(cool)\b/g
정규식 수
는 body
이 텍스트가 포함되어 있다고 가정하자 우리는 대체 표현식에서 이것을 $1
으로 참조 할 것입니다. data-styled-text
속성을 가진 span
내에 포함되지 않은 텍스트 노드를 통해
그 개념의 주위에 장난 삼아하고 난 당신이 특정 텍스트를 대상으로하는 regex
을 사용하여 원하는 어떤 방법으로 텍스트를 조작 할 수있는 방법을 보여줍니다 당신을 위해 바이올린을 만들 수 있습니다. 나는 당신이 페이지에 텍스트로 원하는대로 무엇이든 할 수있게 해주는 2 가지 주요 기능인 wrapText
과 styleText
을 만들었습니다. 그것은 더 최적화 될 수 있지만 아이디어를 얻을 것입니다.
다음 기능을 사용하면 텍스트 노드의 텍스트를 포장 할 수 있습니다 http://jsfiddle.net/scarsick/tX4Ge/1/
에서보세요.
function wrapText(textNode, textRx, wrapFn) {
var global = textRx.global,
wrapEl,
result,
rightTextNode,
matchedText,
index;
while (result = textRx.exec(textNode.nodeValue)) {
rightTextNode = textNode.splitText(index = result.index);
rightTextNode.nodeValue = rightTextNode.nodeValue.substring((matchedText = result[0]).length);
wrapEl = wrapFn(matchedText, index);
wrapEl.appendChild(document.createTextNode(matchedText));
rightTextNode.parentNode.insertBefore(wrapEl, rightTextNode);
if (!global) {
break;
}
textNode = rightTextNode;
textRx.lastIndex = 0;
}
}
다음 기능을 사용하여 요소 내에 포함 된 텍스트의 스타일을 지정할 수 있습니다.
function styleText(el, textRx, styleFn) {
var wrapEl = document.createElement('span'),
slice = [].slice;
wrapEl.setAttribute('data-styled-text', 'true');
styleText = function(el, textRx, styleFn) {
var childNodes = slice.call(el.childNodes, 0),
i = 0,
len = childNodes.length,
node;
for (; i < len; i++) {
node = childNodes[i];
switch (node.nodeType) {
case 3:
if (!node.parentNode.getAttribute('data-styled-text')) {
wrapText(node, textRx, function (text, index) {
var el = wrapEl.cloneNode();
styleFn(el, text, index);
return el;
});
continue;
}
styleFn(node.parentNode);
break;
case 1:
styleText(node, textRx, styleFn);
break;
}
}
};
styleText(el, textRx, styleFn);
}
'# textWithTheWord'는'span'을 포함하고있는'element'이고,'color'를 설정하는'style' 속성을 가지고 있습니다. 그런 다음'span' 요소에 대한'color' 값을 수정하고 싶습니다. 그게 맞습니까? 그렇다면 문자열을 조작하여이 작업을 수행하려는 이유가 있습니까? – plalx
@plalx 네, 지금까지, 당신 말이 맞아요. [링크] (http://stackoverflow.com/questions/10328281/need-to-replace-font-for-a-particular : 나는 특정 단어의 색상이 여기에 있었다 내가 찾을 수있는 유일한 솔루션을 변경하려 -워드). –
귀하의 문제에 대한 답변을 게시했습니다. 도움이되기를 바랍니다. 최고의 행운! ;) – plalx