Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Помещение текста в буфер по клику на него (https://javascript.ru/forum/events/73501-pomeshhenie-teksta-v-bufer-po-kliku-na-nego.html)

Ola 20.04.2018 11:49

Помещение текста в буфер по клику на него
 
Здравствуйте! Хотела сделать - помещение текста в буфер по клику на него, нашла вот такой код:
const span = document.querySelector("span");

span.onclick = function() {
  document.execCommand("copy");
}

span.addEventListener("copy", function(event) {
  event.preventDefault();
  if (event.clipboardData) {
    event.clipboardData.setData("text/plain", span.textContent);
    console.log(event.clipboardData.getData("text"))
  }
});

<span>text</span>


Но почему-то у меня это не работает. Но если на странице, где я это нашла (https://stackoverflow.com/questions/...tring-on-click) нажать "Run code snippet" - то на этой странице работает...:(

Мой файл onclick-copy.html выглядит так:
<html>
<head>
	<meta charset="utf-8">



</head>
<body>

<script>
const span = document.querySelector("span");

span.onclick = function() {
  document.execCommand("copy");
}

span.addEventListener("copy", function(event) {
  event.preventDefault();
  if (event.clipboardData) {
    event.clipboardData.setData("text/plain", span.textContent);
    console.log(event.clipboardData.getData("text"))
  }
});
</script>

<span>text</span>

</body>
</html>

Подскажите пожалуйста...

Dilettante_Pro 20.04.2018 12:01

Найдите одно отличие
<html>
<head>
	<meta charset="utf-8">



</head>
<body>
   <span>text</span>
<script>
const span = document.querySelector("span");

span.onclick = function() {
  document.execCommand("copy");
}

span.addEventListener("copy", function(event) {
  event.preventDefault();
  if (event.clipboardData) {
    event.clipboardData.setData("text/plain", span.textContent);
    console.log(event.clipboardData.getData("text"))
  }
});
</script>
</body>
</html>

Ola 20.04.2018 12:30

А-а-а! Точно! Теперь работает! Спасибо! Я редко программирую, поэтому получаются такие казусы... Но, возможно, у меня еще появится вопрос по этой теме...


Часовой пояс GMT +3, время: 08:13.