내용

html div 내부에 정의된 page를 code형태로 추출하여 클립보드로 복사하는 기능

 

방법

html

<div id="test_div" name="test_div">
      ~~~~~~~~
</div>

 

javascript

function page_code_copy(){

    file = window.location.href;

    var copyText = document.getElementById("test_div");

    var textArea = document.createElement("textarea");

    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;

    // Ensure it has a small width and height. Setting to 1px / 1em
    // doesn't work as this gives a negative w/h on some browsers.
    textArea.style.width = '2em';
    textArea.style.height = '2em';

    // We don't need padding, reducing the size if it does flash render.
    textArea.style.padding = 0;

    // Clean up any borders.
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';

    // Avoid flash of white box if rendered for any reason.
    textArea.style.background = 'transparent';

    textArea.value = copyText.innerHTML;
    document.body.appendChild(textArea);

    textArea.select();

    try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
        showAlert('Page Code Copy', 'Page Code Copy Successful !!', 2, 2000);
    } catch (err) {
        console.log('Oops, unable to copy');
    }

      document.body.removeChild(textArea);

    /* Select the text field */
    //copyText.select();
    //copyText.setSelectionRange(0, 99999); /* For mobile devices */

    /* Copy the text inside the text field */
    //navigator.clipboard.writeText(copyText.innerHTML);
    //showAlert('Report Copy', 'Report Copy Successful !!', 2, 2000);
}

참고

https://gist.github.com/vitsalis/1b44302d92213d0a09128a4284f15ad6

내용

html 페이지를 복사 이후 메일내용에 첨부하고 싶을때,

렌더링된 이후 페이지와 동일한 형태를 클립보드에 복사하여 붙여넣기

 

방법

html

<div id="test_div" name="test_div">
      ~~~~~~~~
</div>

 

javascript

function page_page(){

    var htmlEditor = document.getElementById("test_div")

    var container = document.createElement('div')
    container.innerHTML = htmlEditor.outerHTML
    container.style.position = 'fixed'
    container.style.pointerEvents = 'none'
    container.style.opacity = 0
    document.body.appendChild(container)
    window.getSelection().removeAllRanges()
    var range = document.createRange()
    range.selectNode(container)
    window.getSelection().addRange(range)
    document.execCommand('copy')
    document.body.removeChild(container);

    showAlert('Page Copy', 'Page Copy Successful !!', 2, 2000);
}

참고

https://stackoverflow.com/questions/62833657/is-there-any-way-to-copy-the-rendered-html-of-a-div

내용

html page를 이미지 형태로 변환하여 저장 or 확인하는 기능

 

방법

html2canvas 사용

 

html

<!-- jQuery -->
<script src="~/plugins/jquery/jquery.min.js"></script>
<!-- html2canvas -->
<script src="~/plugins/html2canvas/html2canvas.min.js"></script>


<div id='myCanvas' class='target' style='border:1px solid gray;width:200px;height:200px'>
    <div style='border:1px solid green;width:180px;height:250px'>Hello world</div>
</div>

 

javascript

    saveAS 함수를 생성해두고 호출하는 방식

    canvas_height, canvas_widtht 의 경우 설정하지 않아도 상관없으나, 옵션 설정 방법을 위해 작성됨

function saveAs(uri, filename) {
    var link = document.createElement('a');
    if (typeof link.download === 'string') {
        link.href = uri;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
else {
        window.open(uri);
    }
}

function page_snapshot()
{
    const canvas_height = document.querySelector('#myCanvas').offsetHeight
    const canvas_widtht = document.querySelector('#myCanvas').offsetWidth

    html2canvas(document.querySelector("#myCanvas"),{"width": canvas_widtht, "height": canvas_height}).then(canvas => {
        canvas_filename = 'myCanvas_img.jpeg'
        saveAS(canvas.toDataURL("image/jpeg"), canvas_filename);
    });
}

참고

https://lts0606.tistory.com/270

https://html2canvas.hertzen.com/

https://every-time-i-pass-this-place.tistory.com/entry/html2canvas-%EC%82%AC%EC%9A%A9%EB%B2%95-%EC%BA%A1%EC%B2%98%EB%A5%BC-%EC%9D%B4%EB%AF%B8%EC%A7%80%EB%A1%9C-%EB%8B%A4%EC%9A%B4%EB%A1%9C%EB%93%9C

1. <div> 태그란?

<div>tag란 division, 분할, 분배, 분류를 뜻합니다. html 안에 존재하는 여러 개의 태그들을 <div>라는 큰 단위로 묶어주는 주머니 역할을 한다. 큰 단위인 <div>로 묶어주면, 나중에 css로 <div>에만 수식을 해도 <div>태그 안에 속해있는 태그들이 모두 같은 명령을 받아 동일하게 적용된다.

만약 코드가 1,000줄이 넘고 코드도 다른 코드 30개들이 있는데 여기에 모두 동일한 효과를 적용시켜야 된다고 하면, 코드 하나하나에 효과를 넣는 게 아니라 <div> 태그로 묶어 나중에 css로 30여 개의 코드에 동일한 효과를 적용시킬 때 사용한다.

<div> 태그는 block level element (블록 라벨 엘리먼트)라 해당하는 코드의 행 전체를 차지한다. 다만, <div> 태그는 이렇게 묶어주는 주머니 역할이기 때문에 <div>태그 자체로는 시각적인 변화를 나타낼 수 없다.

 

 

2. <span> 태그란?

<span> 태그도 <div>태그와 같이 여러 개의 태그들을 묶어주는 주머니 역할을 한다. <span>태그는 inline element (인라인 엘리먼트)라 자신의 content 만큼 공간을 차지한다. <span> 태그는 이렇게 묶어주는 주머니 역할이기 때문에 <span>태그 자체로는 시각적인 변화를 나타낼 수 없다.

3. <div>, <span> tag 출력하기

■ <div> tag 출력하기

<div> 텍스트 텍스트 </div>
<div> 텍스트 텍스트 </div>

■ <span> tag 출력하기

 

<span> 텍스트 텍스트 </span>
<span> 텍스트 텍스트 </span>

4.<p>, <div>, <span>tag의 차이점

<p>, <div>, <span> 태그가 뭐가 다른 건지 의문을 품게 될 때가 있다. 웹 제작 수업 선생님께 여쭤보니 아래처럼 가르쳐주셨다. 궁금하셨던 분들은 참고하시면 좋을듯하다.

■ <p> : 문단 분량의 content + 상하 margin이 있음

▲ <p> tag css box 조회화면 / 파란색 : content, 주황색 : margin

■ <div> : block level element (블록 라벨 엘리먼트) - 화면 전체를 쓰는 애들. content에 해당하는 <div>라는 텍스트가 행 전체를 차지하고 있다.

▲ <div> tag css box 조회화면 / 파란색 : content

■ <span> : inline element (인라인 엘리먼트) - 자기 content 만큼의 테두리를 쓰는 애들. content에 해당하는 <span>이라는 텍스트가 자기만큼의 공간을 차지하는 것을 볼 수 있다.

내용

이벤트 발생 시점 div 에 정의된 내용을 출력 or 숨김 하고 싶은 경우

 

방법

html

<div class="row" id="test_div">
          ~~~~~
</div>

 

javascript

화면 출력
document.getElementById("test_div").style.display = "";

화면 숨김
document.getElementById("test_div").style.display = "none";

참고

https://www.w3schools.com/jsref/prop_style_display.asp

 

 

내용

일시적으로 실행을 멈추거나, 일정 시간동안 실행을 지연시키는 기능

 

방법

setTimeout( 실행 명령어, 지연 시간(마이크로초) )

'after'를 출력하는 문구는 3초후에 실행이됨, 하지만 'done' 문구가 먼저 출력된 이유는 javascript는 기본적으로 프로그램 실행을 막지 않는(non-block)방식이라 다음 코드가 먼저 실행됨

console.log("before");
setTimeout(() => console.log("after"), 3000);
console.log("done!");

-- 결과 --

before
done!
after

 

Promise 를 사용한 sleep( 지연 시간(마이크로초) ) 

비동기 지연

function sleep(ms) {
  return new Promise((r) => setTimeout(r, ms));
}

console.log("before");
sleep(3000)
  .then(() => console.log("after"))
  .then(() => console.log("done!"));

-- 결과 --

before
after
done!

 

참고

https://www.daleseo.com/js-sleep/

 


to Top