Node.js TreeWalker 및 / 또는 document.createRange ()가 단일 요소를 선택하지 않습니다.

겨울

단일 내부 노드가있는 div가 있습니다.

<section id="Source" class="source">
  <div>
    test
  </div>
</section>

나는 그것의 내용을 얻기 위해 노력하고 있어요와 document.createRange()document.createTreeWalker()아래에 따라 :

function findEndNode(source, maxHeight) {
  const range = document.createRange();
  range.selectNodeContents(source);

  var nodes = document.createTreeWalker(
    source,
    NodeFilter.SHOW_ELEMENT,
    null,
    null
  );

  while (node = nodes.nextNode()) {
    range.setEndBefore(nodes.currentNode);
    const {
      height
    } = range.getBoundingClientRect();
    const rangeHeight = height;

    if (maxHeight <= rangeHeight) {
      console.log('out of  bounds');
      const newNode = nodes.previousNode();
      range.setEndBefore(nodes.currentNode);
      break;
    } else {
      console.log('within bounds');
      continue;
    }
  }

  return range;
};

그러나 도중 어딘가에서 가장 안쪽 노드가 손실됩니다.

전체 코드 (스 니펫에 포함)에서 볼 수 있듯이 "테스트"범위는 소스 내부에 남아 있지만 복제로 이동해야합니다.

const source = document.getElementById('Source');
const target = document.getElementById('Target');
const wrapper = document.getElementById('Wrapper');

wordWrap(source);
splitContent(source, target, wrapper);
//splitContent(source, target, wrapper);

function splitContent(source, target, wrapper) {
  const {
    height
  } = target.getBoundingClientRect();
  const maxHeight = height;

  const range = document.createRange();
  const endNode = findEndNode(source, maxHeight);
  
  range.setStart(source, 0);
  range.setEnd(endNode.endContainer, endNode.endOffset);

  const content = range.extractContents();
  const clone = target.cloneNode(false);
  clone.id = 'Clone';
  clone.appendChild(content);
  wrapper.appendChild(clone);

  const hasChildren = source.hasChildNodes();
};


function findEndNode(source, maxHeight) {
  const range = document.createRange();
  range.selectNodeContents(source);

  var nodes = document.createTreeWalker(
    source,
    NodeFilter.SHOW_ELEMENT,
    null,
    null
  );

  while (node = nodes.nextNode()) {
    range.setEndBefore(nodes.currentNode);
    const {
      height
    } = range.getBoundingClientRect();
    const rangeHeight = height;

    if (maxHeight <= rangeHeight) {
      console.log('out of  bounds');
      const newNode = nodes.previousNode();
      range.setEndBefore(nodes.currentNode);
      break;
    } else {
      console.log('within bounds');
      continue;
    }
  }

  return range;
};



function wordWrap(element) {
  var nodes = document.createTreeWalker(
    element,
    NodeFilter.SHOW_TEXT,
    null,
    null
  );
  var node;
  while (node = nodes.nextNode()) {
    var p = node.parentNode;
    var text = node.nodeValue;
    var m;
    while (m = text.match(/^(\s*)(\S+)/)) {
      text = text.slice(m[0].length);
      p.insertBefore(document.createTextNode(m[1]), node);
      var word = p.insertBefore(document.createElement('span'), node);
      word.appendChild(document.createTextNode(m[2]));
      word.className = 'word';
    }
    node.nodeValue = text;
  }
}
section {
  font-family: arial;
  font-size: 11pt;
}

.target {
  height: 400px;
  width: 400px;
  border: 2px dashed green;
  margin: 20px;
}

.source {
  border: 2px dashed blue;
  width: 400px;
  margin: 20px;
}
#Clone {
  border-color: red;
}
<section id="Source" class="source">
  <div>
    test
  </div>
</section>

<div id="Target" class="target">
</div>

<section id="Wrapper">
</section>

신선한

엔드 오프셋이 꺼져 있습니다. 에서 findEndNodes당신은 당신의 현재 코드 오프셋의 수는 setEndAfter를 사용해야 할 때 setEndBefore을 사용하고 있기 때문입니다, 덜 필요한 것보다 하나입니다 가정 노드를 찾을 때.

const source = document.getElementById('Source');
const target = document.getElementById('Target');
const wrapper = document.getElementById('Wrapper');

wordWrap(source);
splitContent(source, target, wrapper);
//splitContent(source, target, wrapper);

function splitContent(source, target, wrapper) {
  const {
    height
  } = target.getBoundingClientRect();
  const maxHeight = height;

  const range = document.createRange();
  const endNode = findEndNode(source, maxHeight);
  
  range.setStart(source, 0);
  range.setEnd(endNode.endContainer, endNode.endOffset);

  const content = range.extractContents();
  const clone = target.cloneNode(false);
  clone.id = 'Clone';
  clone.appendChild(content);
  wrapper.appendChild(clone);

  const hasChildren = source.hasChildNodes();
};


function findEndNode(source, maxHeight) {
  const range = document.createRange();
  range.selectNodeContents(source);

  var nodes = document.createTreeWalker(
    source,
    NodeFilter.SHOW_ELEMENT,
    null,
    null
  );

  while (node = nodes.nextNode()) {
    range.setEndAfter(nodes.currentNode);
    const {
      height
    } = range.getBoundingClientRect();
    const rangeHeight = height;

    if (maxHeight <= rangeHeight) {
      console.log('out of  bounds');
      const newNode = nodes.previousNode();
      range.setEndAfter(nodes.currentNode);
      break;
    } else {
      console.log('within bounds');
      continue;
    }
  }

  return range;
};



function wordWrap(element) {
  var nodes = document.createTreeWalker(
    element,
    NodeFilter.SHOW_TEXT,
    null,
    null
  );
  var node;
  while (node = nodes.nextNode()) {
    var p = node.parentNode;
    var text = node.nodeValue;
    var m;
    while (m = text.match(/^(\s*)(\S+)/)) {
      text = text.slice(m[0].length);
      p.insertBefore(document.createTextNode(m[1]), node);
      var word = p.insertBefore(document.createElement('span'), node);
      word.appendChild(document.createTextNode(m[2]));
      word.className = 'word';
    }
    node.nodeValue = text;
  }
}
section {
  font-family: arial;
  font-size: 11pt;
}

.target {
  height: 400px;
  width: 400px;
  border: 2px dashed green;
  margin: 20px;
}

.source {
  border: 2px dashed blue;
  width: 400px;
  margin: 20px;
}
#Clone {
  border-color: red;
}
<section id="Source" class="source">
  <div>
    test
  </div>
</section>

<div id="Target" class="target">
</div>

<section id="Wrapper">
</section>

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

jquery가 js 파일 내에서 요소를 선택하지 않습니다.

분류에서Dev

index.html 파일을 읽고 새 요소를 추가하는 node.js 메소드가 있습니까?

분류에서Dev

Express, Jest 및 SuperTest가 포함 된 Node.js는 실패하지 않습니다.

분류에서Dev

JQuery는 추가 된 숨겨진 요소를 선택하지 않습니다.

분류에서Dev

jquery 및 node.js 데이터가 오류를 전달하지 않습니다.

분류에서Dev

XSD가 요소 목록 또는 단일 요소를 루트로 지정할 수 있습니까?

분류에서Dev

deleteItem-제공된 키 요소가 스키마 (Node.js)와 일치하지 않습니다.

분류에서Dev

Angular 4 RC.4 및 .net core 선택기 "app"이 일치하는 요소가 없습니다.

분류에서Dev

jquery는 이전 요소가 선택자와 일치하는 각 요소를 선택합니다.

분류에서Dev

tr 및 / 또는 td를 선택하고 요소를 숨 깁니다.

분류에서Dev

'\ "node build \ bundle.js \"'는 내부 또는 외부 명령, 작동 가능한 프로그램 또는 배치 파일로 인식되지 않습니다.

분류에서Dev

grunt 또는 gulp를 사용하지 않고 Node JS에서 LESS 및 SCSS 파일을 어떻게 LINT 할 수 있습니까?

분류에서Dev

jQuery의 $ ()와 달리 document.getElementById () 및 document.querySelector ()가 노드를 반환하지 않아 바닐라 JS에 자식을 추가 할 수 없습니다.

분류에서Dev

jquery 선택기가 작동하지만 document.getElementById는 ES6 이벤트를 추가하지 않습니다.

분류에서Dev

사용자 정의 node.js 웹 서버가 CSS 및 JavaScript로드를 완료하지 않습니다.

분류에서Dev

Nuxt.js는 "구성 요소를 마운트하지 못했습니다 : 템플릿 또는 렌더링 기능이 정의되지 않았습니다."라는 오류가있는 구성 요소를 찾을 수 없습니다.

분류에서Dev

$ (document) .innerHeight () 및 $ (window) .innerHeight ()가 모바일에서 작동하지 않습니다.

분류에서Dev

각도에 다른 구성 요소를 추가하는 방법 및 이전 구성 요소와 동일한 데이터 및 추가 정보가 있습니다.

분류에서Dev

선택기와 일치하는 요소를 찾지 못했습니다.

분류에서Dev

라디오 버튼, 확인란 및 선택 요소가 적절하게 채워지지 않습니다.

분류에서Dev

ID가있는 요소를 선택하는 CSS 스타일이 있습니까?

분류에서Dev

Node.js에서 단일 요청으로 Google Vision API 라벨 감지 및 세이프 서치 감지를 실행하는 방법은 무엇입니까?

분류에서Dev

custom _document.js를 사용하는 NextJS에서 componentDidMount가 작동하지 않습니다.

분류에서Dev

Node js 라우터 비동기 및 대기가 작동하지 않습니다.

분류에서Dev

내 socket.io 및 node.js 코드가 작동하지 않습니다-왜?

분류에서Dev

클래스가 동일한 모든 요소를 선택하고 일부는 두 클래스를 갖습니다.

분류에서Dev

Node.js를 설치하는 Docker (구성)가 npm을 중단했습니다.

분류에서Dev

구성 요소가 반복되지 않고 소품 (Vue 또는 기타 js 라이브러리)이없는 경우에도 구성 요소를 사용하여 긴 HTML을 단순화합니다. 예 혹은 아니오?

분류에서Dev

Python stdout 및 for 루프는 목록의 첫 번째 요소를 인쇄하지 않습니다 (두 번째 요소가 첫 번째 요소를 대체 함).

Related 관련 기사

  1. 1

    jquery가 js 파일 내에서 요소를 선택하지 않습니다.

  2. 2

    index.html 파일을 읽고 새 요소를 추가하는 node.js 메소드가 있습니까?

  3. 3

    Express, Jest 및 SuperTest가 포함 된 Node.js는 실패하지 않습니다.

  4. 4

    JQuery는 추가 된 숨겨진 요소를 선택하지 않습니다.

  5. 5

    jquery 및 node.js 데이터가 오류를 전달하지 않습니다.

  6. 6

    XSD가 요소 목록 또는 단일 요소를 루트로 지정할 수 있습니까?

  7. 7

    deleteItem-제공된 키 요소가 스키마 (Node.js)와 일치하지 않습니다.

  8. 8

    Angular 4 RC.4 및 .net core 선택기 "app"이 일치하는 요소가 없습니다.

  9. 9

    jquery는 이전 요소가 선택자와 일치하는 각 요소를 선택합니다.

  10. 10

    tr 및 / 또는 td를 선택하고 요소를 숨 깁니다.

  11. 11

    '\ "node build \ bundle.js \"'는 내부 또는 외부 명령, 작동 가능한 프로그램 또는 배치 파일로 인식되지 않습니다.

  12. 12

    grunt 또는 gulp를 사용하지 않고 Node JS에서 LESS 및 SCSS 파일을 어떻게 LINT 할 수 있습니까?

  13. 13

    jQuery의 $ ()와 달리 document.getElementById () 및 document.querySelector ()가 노드를 반환하지 않아 바닐라 JS에 자식을 추가 할 수 없습니다.

  14. 14

    jquery 선택기가 작동하지만 document.getElementById는 ES6 이벤트를 추가하지 않습니다.

  15. 15

    사용자 정의 node.js 웹 서버가 CSS 및 JavaScript로드를 완료하지 않습니다.

  16. 16

    Nuxt.js는 "구성 요소를 마운트하지 못했습니다 : 템플릿 또는 렌더링 기능이 정의되지 않았습니다."라는 오류가있는 구성 요소를 찾을 수 없습니다.

  17. 17

    $ (document) .innerHeight () 및 $ (window) .innerHeight ()가 모바일에서 작동하지 않습니다.

  18. 18

    각도에 다른 구성 요소를 추가하는 방법 및 이전 구성 요소와 동일한 데이터 및 추가 정보가 있습니다.

  19. 19

    선택기와 일치하는 요소를 찾지 못했습니다.

  20. 20

    라디오 버튼, 확인란 및 선택 요소가 적절하게 채워지지 않습니다.

  21. 21

    ID가있는 요소를 선택하는 CSS 스타일이 있습니까?

  22. 22

    Node.js에서 단일 요청으로 Google Vision API 라벨 감지 및 세이프 서치 감지를 실행하는 방법은 무엇입니까?

  23. 23

    custom _document.js를 사용하는 NextJS에서 componentDidMount가 작동하지 않습니다.

  24. 24

    Node js 라우터 비동기 및 대기가 작동하지 않습니다.

  25. 25

    내 socket.io 및 node.js 코드가 작동하지 않습니다-왜?

  26. 26

    클래스가 동일한 모든 요소를 선택하고 일부는 두 클래스를 갖습니다.

  27. 27

    Node.js를 설치하는 Docker (구성)가 npm을 중단했습니다.

  28. 28

    구성 요소가 반복되지 않고 소품 (Vue 또는 기타 js 라이브러리)이없는 경우에도 구성 요소를 사용하여 긴 HTML을 단순화합니다. 예 혹은 아니오?

  29. 29

    Python stdout 및 for 루프는 목록의 첫 번째 요소를 인쇄하지 않습니다 (두 번째 요소가 첫 번째 요소를 대체 함).

뜨겁다태그

보관