Копировать в буфер обмена по клику с подсказками псевдоэлементов - PullRequest
2 голосов
/ 22 июня 2019

Я пытаюсь создать всплывающую подсказку, созданную с помощью псевдоэлемента, по которой можно кликать, чтобы затем запустить функцию для копирования в буфер обмена.

Я уже пытался добавить onClick внутри псевдоэлемента CSS, а также в промежуток как onClick.

function myFunction() {
  var copyText = document.getElementById("firstnamereflect");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
[data-tooltip] {
  display: inline-block;
  position: relative;
  cursor: help;
  padding: 4px;
}


/* Tooltip styling */

[data-tooltip]:before {
  content: attr(data-tooltip);
  display: none;
  position: absolute;
  background: #000;
  color: #fff;
  padding: 4px 8px;
  font-size: 14px;
  line-height: 1.4;
  min-width: 100px;
  text-align: center;
  border-radius: 4px;
}


/* Dynamic horizontal centering */

[data-tooltip-position="top"]:before,
[data-tooltip-position="bottom"]:before {
  left: 50%;
  -ms-transform: translateX(-50%);
  -moz-transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
}

[data-tooltip-position="bottom"]:before {
  top: 100%;
  margin-top: 6px;
}


/* Tooltip arrow styling/placement */

[data-tooltip]:after {
  content: '';
  display: none;
  position: absolute;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
}


/* Dynamic horizontal centering for the tooltip */

[data-tooltip-position="top"]:after,
[data-tooltip-position="bottom"]:after {
  left: 50%;
  margin-left: -6px;
}

[data-tooltip-position="top"]:after {
  bottom: 100%;
  border-width: 6px 6px 0;
  border-top-color: #000;
}

[data-tooltip-position="bottom"]:after {
  top: 100%;
  border-width: 0 6px 6px;
  border-bottom-color: #000;
}


/* Show the tooltip when hovering */

[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
  display: block;
  z-index: 50;
}
<div class="fixed">
  <span onclick="myFunction()" data-tooltip="Copy" data-tooltip-position="bottom" id="firstnamereflect"></span> </div>

Я ожидаю, что когда я нажму на всплывающую подсказку «Копировать», созданную подсказкой данных, она запустит функцию.

Ответы [ 3 ]

0 голосов
/ 22 июня 2019

Я изменил ваш скрипт и заставил его работать.copyText.select(); работает только с текстовыми полями, такими как ввод, текстовое поле и т. Д. Вы можете извлечь значение из div / span, используя диапазон

Измените свою функцию на

function myFunction() {
  var copyText = document.getElementById("firstnamereflect").firstChild;
  var range = document.createRange();
  var endOffset = copyText.length;
  range.setStart(copyText, 0);
  range.setEnd(copyText, endOffset);
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  alert("Copied the text: " + range);
}

function myFunction() {
  var copyText = document.getElementById("firstnamereflect").firstChild;
  var range = document.createRange();
  var endOffset = copyText.length;
  range.setStart(copyText, 0);
  range.setEnd(copyText, endOffset);
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  alert("Copied the text: " + range);
}
[data-tooltip] {
  display: inline-block;
  position: relative;
  cursor: help;
  padding: 4px;
}


/* Tooltip styling */

[data-tooltip]:before {
  content: attr(data-tooltip);
  display: none;
  position: absolute;
  background: #000;
  color: #fff;
  padding: 4px 8px;
  font-size: 14px;
  line-height: 1.4;
  min-width: 100px;
  text-align: center;
  border-radius: 4px;
}


/* Dynamic horizontal centering */

[data-tooltip-position="top"]:before,
[data-tooltip-position="bottom"]:before {
  left: 50%;
  -ms-transform: translateX(-50%);
  -moz-transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
}

[data-tooltip-position="bottom"]:before {
  top: 100%;
  margin-top: 6px;
}


/* Tooltip arrow styling/placement */

[data-tooltip]:after {
  content: '';
  display: none;
  position: absolute;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
}


/* Dynamic horizontal centering for the tooltip */

[data-tooltip-position="top"]:after,
[data-tooltip-position="bottom"]:after {
  left: 50%;
  margin-left: -6px;
}

[data-tooltip-position="top"]:after {
  bottom: 100%;
  border-width: 6px 6px 0;
  border-top-color: #000;
}

[data-tooltip-position="bottom"]:after {
  top: 100%;
  border-width: 0 6px 6px;
  border-bottom-color: #000;
}


/* Show the tooltip when hovering */

[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
  display: block;
  z-index: 50;
}
<div class="fixed">
  <span onclick="myFunction()" data-tooltip="Copy" data-tooltip-position="bottom" id="firstnamereflect">Hover Me</span>
</div>
0 голосов
/ 22 июня 2019

Спасибо, Джину! Это работало отлично, когда я изменил предупреждение на document.execCommand («copy»); строка. Теперь мне просто нужно разобрать его, чтобы я мог понять, что вы сделали!

function myFunction() {
  var copyText = document.getElementById("firstnamereflect").firstChild;
  var range = document.createRange();
  var endOffset = copyText.length;
  range.setStart(copyText, 0);
  range.setEnd(copyText, endOffset);
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  alert("Copied the text: " + range);
}
[data-tooltip] {
  display: inline-block;
  position: relative;
  cursor: help;
  padding: 4px;
}


/* Tooltip styling */

[data-tooltip]:before {
  content: attr(data-tooltip);
  display: none;
  position: absolute;
  background: #000;
  color: #fff;
  padding: 4px 8px;
  font-size: 14px;
  line-height: 1.4;
  min-width: 100px;
  text-align: center;
  border-radius: 4px;
}


/* Dynamic horizontal centering */

[data-tooltip-position="top"]:before,
[data-tooltip-position="bottom"]:before {
  left: 50%;
  -ms-transform: translateX(-50%);
  -moz-transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
}

[data-tooltip-position="bottom"]:before {
  top: 100%;
  margin-top: 6px;
}


/* Tooltip arrow styling/placement */

[data-tooltip]:after {
  content: '';
  display: none;
  position: absolute;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
}


/* Dynamic horizontal centering for the tooltip */

[data-tooltip-position="top"]:after,
[data-tooltip-position="bottom"]:after {
  left: 50%;
  margin-left: -6px;
}

[data-tooltip-position="top"]:after {
  bottom: 100%;
  border-width: 6px 6px 0;
  border-top-color: #000;
}

[data-tooltip-position="bottom"]:after {
  top: 100%;
  border-width: 0 6px 6px;
  border-bottom-color: #000;
}


/* Show the tooltip when hovering */

[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
  display: block;
  z-index: 50;
}
<div class="fixed">
  <span onclick="myFunction()" data-tooltip="Copy" data-tooltip-position="bottom" id="firstnamereflect">Hover Me</span>
</div>
0 голосов
/ 22 июня 2019

Вот как бы я это сделал.Я думаю, что вы можете просто прикрепить обработчик событий к самой подсказке.Как только на дисплее ничего не отображается, он не будет отображаться для пользователя, поэтому ничего не произойдет, если пользователь нажмет на пробел.

Код JS:

// attach an event handler that'll show the tooltip 
document.querySelector("#hoverText").onmouseover = () => {
  document.querySelector("#toolTip").style.display = "inline-block";
}

// attach an event handler that'll hide the tooltip 
document.querySelector("#hoverText").onmouseout = () => {
  document.querySelector("#toolTip").style.display = "none";
}

// attach the copy function
document.querySelector("#toolTip").onclick = copyToClipboard;

...