project/miniCode

브라우저에서 복사버튼 만들기.

부엉이사장 2022. 7. 29. 02:33

참고로 vuejs에서 만들었기때문에 일반적인 html, js의 페이지에선 

코드가 살짝 다를 수 있다.

 

 

먼저 템플릿

 

복사방법에는 두가지가 있는데 둘다쓴다.

 

#1 span태그 복사

  <span id="span">여긴 span태그 복사야~</span>
  <button v-on:click="copy1()">Copy1</button>

이 코드의 메서드는 이렇다.

    const copy1 = () => {
      let copyText = document.getElementById("span").innerHTML;
      navigator.clipboard.writeText(copyText).then(
        console.log('복사완료')
      )
    }

먼저 span태그안에있는 값을 변수로 지정해주고 밑에 프로미스에 담으면 된다.

 

 

 

#2 input값 복사

  <input id="input" value="여긴 input복사야~" type="text" />
  <button v-on:click="copy2()">Copy2</button>

메서드는

    const copy2 = () => {
      let copyText = document.getElementById("input");
      copyText.select();
      document.execCommand("copy");
      alert("complete copying")
    }

 

 

 

 

??? 왜 두가지를 배웠니?

맨처음에 input창의 코드를 구글링으로 찾았었다.

근데 현재 html의 태그안에 내용값을 가져오려고 해봤는데 안되더라..

.select()이랑 execCommand메서드가 안되는듯..?

 

그래서 커뮤니티에 물어보니 

1번방법을 알려줘서 독스읽어봤다. 

1번방법이 코드도 간결하고 좋은것같다

다만 브라우저호환성이 파이어폭스에서 아주 약간 문제가 있더라..

 

 

 

# 붙여넣기 기능

  <button v-on:click="paste()">paste</button>
  <p id="paste">하잉</p>

이건 템플릿

    const paste = () => {
      console.log('paste')
      navigator.clipboard.readText().then(
        (clipText) => {
          document.getElementById("paste").innerText = clipText
          console.log(clipText)
          }
        );
    }

이건 메서드

단순..