2011-06-10 6 views
0

‘’“”‛‟′″˝과 같은 특수 문자를 어떻게 강조 표시합니까 (또는 특별한 마크 업을 부여합니까)? 감사. .innerHTML.replace() 찾기 및 바꾸기는 이벤트 핸들러와 DOM을 파손하므로 작동하지 않습니다.자바 스크립트 강조 문자


나는 다음을 시도했지만, 그건 그냥 일반 텍스트 대신 코드에서 span 년대로 끝납니다.

function highlightText(node, find, rep){ 
    if(node){ 
     node= node.firstChild; 
     while(node!= null){ 
      if(node.nodeType== 3){ 
       node.data= node.data.replace(find, rep); 
      } 
      else highlightText(node, find, rep); 
      node= node.nextSibling; 
     } 
    } 
    return true; 
} 

highlightText(document.body,/‘/g, "<span style='background: red; color: white;'>‘</span>") 
highlightText(document.body,/’/g, "<span style='background: red; color: white;'>’</span>") 
highlightText(document.body,/“/g, "<span style='background: red; color: white;'>“</span>") 
highlightText(document.body,/”/g, "<span style='background: red; color: white;'>”</span>") 
highlightText(document.body,/‛/g, "<span style='background: red; color: white;'>‛</span>") 
highlightText(document.body,/‟/g, "<span style='background: red; color: white;'>‟</span>") 
highlightText(document.body,/′/g, "<span style='background: red; color: white;'>′</span>") 
highlightText(document.body,/″/g, "<span style='background: red; color: white;'>″</span>") 
highlightText(document.body,/˝/g, "<span style='background: red; color: white;'>˝</span>") 

답변

2

다음은 일부 주요 브라우저에서 작동하는 코드입니다.스택 오버플로 (예 : here, herehere)에이 코드의 변형을 게시했으며, 제 멋대로 만들었습니다 (또는 다른 사람이) 재사용을 위해 많이 변경할 필요가 없습니다.

jsFiddle 예 : http://jsfiddle.net/eh8FE/

코드 : 예를 들어, 사실이 아니다

// Reusable generic function 
function surroundInElement(el, regex, surrounderCreateFunc) { 
    // script and style elements are left alone 
    if (!/^(script|style)$/.test(el.tagName)) { 
     var child = el.lastChild; 
     while (child) { 
      if (child.nodeType == 1) { 
       surroundInElement(child, regex, surrounderCreateFunc); 
      } else if (child.nodeType == 3) { 
       surroundMatchingText(child, regex, surrounderCreateFunc); 
      } 
      child = child.previousSibling; 
     } 
    } 
} 

// Reusable generic function 
function surroundMatchingText(textNode, regex, surrounderCreateFunc) { 
    var parent = textNode.parentNode; 
    var result, surroundingNode, matchedTextNode, matchLength, matchedText; 
    while (textNode && (result = regex.exec(textNode.data))) { 
     matchedTextNode = textNode.splitText(result.index); 
     matchedText = result[0]; 
     matchLength = matchedText.length; 
     textNode = (matchedTextNode.length > matchLength) ? 
      matchedTextNode.splitText(matchLength) : null; 
     surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true)); 
     parent.insertBefore(surroundingNode, matchedTextNode); 
     parent.removeChild(matchedTextNode); 
    } 
} 

// This function does the surrounding for every matched piece of text 
// and can be customized to do what you like 
function createSpan(matchedTextNode) { 
    var el = document.createElement("span"); 
    el.style.backgroundColor = "red"; 
    el.style.color = "white"; 
    el.appendChild(matchedTextNode); 
    return el; 
} 

// The main function 
function wrapSpecialChars(container) { 
    surroundInElement(container, /[‘’“”‛‟′″˝]+/, createSpan); 
} 

wrapSpecialChars(document.body); 
1

HTML에서 텍스트의 서식을 변경하는 유일한 방법은 텍스트를 둘러싼 HTML 요소에서 스타일을 정의하는 것입니다. 따라서 특정 문자 만 강조 표시하려면 각 문자를 HTML 요소 (일반적으로 span)로 묶어야합니다. 어쨌든 더 의미가있을 수도 있습니다.

"이벤트 핸들러와 DOM을 망칠 수 있습니다"라는 것이 무슨 뜻인지 잘 모르겠지만 DOM을 수정하여 문자를 강조해야합니다. 그 주위에 방법이 없습니다.

innerHTML의 전체 트리를 바꾸면 해당 노드가 제거 된 다음 새로운 노드가 추가된다는 것을 알고 있습니다. 그러나 우리는 당신이 이미 다루고있는 것을 모른 채로 대안을 줄 수는 없습니다. 당신이 정말로 전체 페이지에서 일부 문자를 강조하려면


, 당신은 비파괴을 할 필요가 :

  1. 는 모든 자식 노드에 걸쳐 반복적으로
  2. 반복 처리를 작동하는 함수를 만듭니다 노드가 매개 변수로 사용 된 노드
  3. 노드가 요소 인 경우 새 노드로 self recursively를 호출하십시오.
  4. 노드가 텍스트 노드 인 경우 해당 텍스트 노드를 HTML로 바꾸십시오. wrappi 원하는 범위의 문자를 입력하십시오.
  5. 바꿀 내용의 루트 노드로 위의 함수를 호출하십시오.
+0

'.innerHTML.replace()가'페이지에 어떤 임의의 단어를 대체 할 수있다 (A'span'를 추가 포함) 단순히 액세스 할 수없는 페이지의 HTML을 변경할 필요가 없습니다. 그러나 그렇게하면 DOM과 모든 이벤트 핸들러를 파괴하여 나머지 페이지를 무력화시킵니다. 이것을하기위한 좋은 방법이 있어야합니다. – user793238

+0

@ user793238 그럼 사실이 아닐까요? 나는 그것이 내가 말한 것과 모순된다고 생각하지 않는다. innerHTML을 설정하면 트리의 해당 부분에있는 모든 노드가 바뀝니다. – Nicole

+0

@Renesis 당신은 문자가 'span'으로 감싸 져야한다고 말했 읍니다. 그렇지 않은 경우에도이 작업을 수행 할 수 있지만 이렇게하면 DOM 및 모든 이벤트 핸들이 손상됩니다. 당신이 도울 수 있도록 당신이 무엇을 요구하고 있는지 확실하지 않습니다. – user793238

-1

특수 개체 기능을 사용할 수 있습니다. JQuery는 짧은 방법으로 도울 수 있습니다.

예를 들어 페이지로드시 강조 표시 할 개체 스타일을 변경할 수 있습니다. 여기에 주요 아이디어가 있습니다.

function highlightSpan(content) 
{ 
    return "<span style='background: yellow'>" + content + "</span>"; 
} 

function hightlight() 
{ 
    var highlightChars = "‘’“”‛‟′″˝"; 
    // change body content (and highlight chars) 

    var bodyContent = $("body").html(); 

    for(var i = 0; i < highlightChars.length; i++) 
    { 
    var highlightChar = highlightChars[ i ]; 
    bodyContent = bodyContent.replace(highlightChar, highlightSpan(highlightChar)); 
    } 

    $("body").html(bodyContent); 

} 

당신은 document.getElementsByTagName ("몸") [0] .innerHTML 대신 $ ("몸") .html 중에서()을 사용할 수 있습니다

<body onload='highlight()'> 
... 
</body> 

.

replace()은 일치하는 첫 번째 문자를 하나만 대체합니다. 그래서 을 사용할 수 있습니다 (/ ('|'| "|"| "|"| ")/g, highlightSpan (something)); 대신 그리고 특별한 정규 표현식 문자 인 ~으로 문제를 해결하십시오.

+0

백엔드가 강조 표시된 문자로 출력 할 때 더 좋습니다. – sergzach

+0

이 문제는 전체 DOM이 제거되고 새 노드로 대체된다는 것입니다. OP가 그/그녀가 처음에 피하고 싶었던 문제라고 언급했다. – Nicole

+0

당신이 정확합니다! 고맙습니다. – sergzach

관련 문제