#javascript #html #css #dynamic-html
#javascript #HTML #css #динамический-html
Вопрос:
Привет, я новичок в javascript, но прилагаю все усилия, я написал javascript для копирования текста внутри <p></p>
элемента. Мой javascript
function copyToClipboard(var1){
let val = document.getElementById(var1).innerHTML;
const selBox = document.createElement('textarea');
selBox.style.position = 'fixed';
selBox.style.left = '0';
selBox.style.top = '0';
selBox.style.opacity = '0';
selBox.value = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
}
Но мне нужна была пользовательская кнопка оповещения при копировании текста.
Мой html
<div class="Engstatus">
<h2 class="statusheading">Latest English Status</h2>
<div id="englishstatus">
<div class="latestatus">
<p id="p1">life os good when hou have books</p>
<button class="copystatus btn" onclick="copyToClipboard('p1')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
<div class="latestatus">
<p id="p2">Google is a open source library. It is a open source by lary page and sergy brime</p>
<button class="copystatus btn" onclick="copyToClipboard('p2')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
<div class="latestatus">
<p id="p3">Cat is better than dog</p>
<button class="copystatus btn" onclick="copyToClipboard('p3')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
</div>
</div>
Мне нужно <span class="copystatusalert">Copied!</span>
было, чтобы они были видны в течение нескольких секунд при нажатии соответствующей кнопки копирования и исчезли.
Для получения дополнительной информации мой Css
.copystatusalert{
position: relative;
background-color: var(--primary-color);
color: #ffffff;
margin-left: 10px;
padding: 3px 3px;
border-radius: 5px;
z-index: 2;
opacity: 1;
pointer-events: auto;
transition: opacity 0.4s, margin-top 0.4s;
}
.copystatusalert:before{
content:"";
position: absolute;
height: 10px;
width: 10px;
background-color: var(--primary-color);
left: -5px;
transform: translateY(50%) rotate(45deg);
z-index: -1;
top: 17%;
}
Ответ №1:
Вот краткое дополнение к copyToClipboard
функции, чтобы просто изменить .copystatusalert
цвет…
function copyToClipboard(var1) {
let val = document.getElementById(var1).innerHTML;
const selBox = document.createElement('textarea');
selBox.style.position = 'fixed';
selBox.style.left = '0';
selBox.style.top = '0';
selBox.style.opacity = '0';
selBox.value = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
// to change the color of .copystatusalert
let copyStatus = document.getElementById(var1).closest(".latestatus").querySelector(".copystatusalert")
copyStatus.style.color = "black";
// Change the color again in 800 milliseconds
setTimeout(function(){
copyStatus.style.color = "white";
},800)
}
.copystatusalert {
position: relative;
background-color: var(--primary-color);
color: #ffffff;
margin-left: 10px;
padding: 3px 3px;
border-radius: 5px;
z-index: 2;
opacity: 1;
pointer-events: auto;
transition: opacity 0.4s, margin-top 0.4s;
}
.copystatusalert:before {
content: "";
position: absolute;
height: 10px;
width: 10px;
background-color: var(--primary-color);
left: -5px;
transform: translateY(50%) rotate(45deg);
z-index: -1;
top: 17%;
}
<div class="Engstatus">
<h2 class="statusheading">Latest English Status</h2>
<div id="englishstatus">
<div class="latestatus">
<p id="p1">life os good when hou have books</p>
<button class="copystatus btn" onclick="copyToClipboard('p1')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
<div class="latestatus">
<p id="p2">Google is a open source library. It is a open source by lary page and sergy brime</p>
<button class="copystatus btn" onclick="copyToClipboard('p2')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
<div class="latestatus">
<p id="p3">Cat is better than dog</p>
<button class="copystatus btn" onclick="copyToClipboard('p3')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
</div>
</div>
Теперь… Поскольку вы «новичок в javascript», я предлагаю вам внимательно изучить это решение.
Цель состоит в том, чтобы создать ОДНУ функцию, которая будет применяться ко всем элементам, которые вы хотите status
… и избегайте управления уникальным идентификатором для всех <p>
… И «уменьшить» повторяющуюся HTML-разметку (кнопки и интервалы оповещений).
Пожалуйста, ознакомьтесь с комментариями ниже для получения пошаговых подробностей и не стесняйтесь задавать вопросы. 😉
// The animation delay for the "copied" alert
let copyAlertAnimationDelay = 400; // ms
// Get all the status elements
let status = document.querySelectorAll(".status");
// For each status, add a button with its event listener
status.forEach(function(elem) {
// Create the button
let btn = document.createElement('button');
btn.setAttribute("class", "copystatus btn");
btn.innerText = "Copy";
// Append the button
elem.after(btn);
// Set the button event listener
btn.addEventListener("click", function() {
// Get the status
let statusToCopy = elem.innerText;
// Create the temporary textarea to copy the text
const selBox = document.createElement('textarea');
// Use a class instead of multiple element.style.property changes
selBox.setAttribute("class", "hiddenCopy");
selBox.value = statusToCopy;
// Append, copy and remove.
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
selBox.remove();
// create a "Copied!" element.
let alert = document.createElement("span");
alert.innerText = "Copied!";
alert.setAttribute("class", "copystatusalert");
// Use the copyAlertAnimationDelay variable to set the CSS transition
// So it matches the setTimeout delay below
alert.style.transition = `all ${copyAlertAnimationDelay/1000}s`;
// The animation timeouts
// Show
this.after(alert);
setTimeout(function() {
alert.style.opacity = 1;
}, 1)
// Hide
// Change opacity
setTimeout(function() {
alert.style.opacity = 0;
// Remove element
setTimeout(function() {
document.querySelector(".copystatusalert").remove();
}, copyAlertAnimationDelay);
}, copyAlertAnimationDelay * 3) // 3 times the animation delay...
});
});
body {
--primary-color: #a7d8f2; /* ADDED */
}
.copystatusalert {
position: relative;
background-color: var(--primary-color);
/*color: #ffffff; REMOVED */
margin-left: 10px;
padding: 3px 3px;
border-radius: 5px;
z-index: 2;
opacity: 0;
/* opacity was 1 */
pointer-events: auto;
/*transition: opacity 0.4s, margin-top 0.4s; REMOVED */
}
.copystatusalert:before {
content: "";
position: absolute;
height: 10px;
width: 10px;
background-color: var(--primary-color);
left: -5px;
transform: translateY(50%) rotate(45deg);
z-index: -1;
top: 17%;
}
/* ADDED */
.hiddenCopy {
position: "fixed";
left: 0;
top: 0;
opacity: 0;
}
<div class="Engstatus">
<h2 class="statusheading">Latest English Status</h2>
<div id="englishstatus">
<div class="latestatus">
<p class="status">life os good when hou have books</p>
</div>
<div class="latestatus">
<p class="status">Google is a open source library. It is a open source by lary page and sergy brime</p>
</div>
<div class="latestatus">
<p class="status">Cat is better than dog</p>
</div>
</div>
</div>
Комментарии:
1. Пожалуйста, проверьте, есть ли какая-либо ошибка в коде. И, пожалуйста, упростите код. Код не работает. Кнопки не видны. (Второй код)
2. Что вы имеете в виду под более простым ? Приведенный выше код работает.
Ответ №2:
Toast используется для отображения подобных задач.
Используйте этот код
function myFunction() {
var x = document.getElementById("message");
x.className = "show";
// you can set the time here//
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
body {
font-family: 'Oswald', sans-serif;
}
#message {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
font-size: 17px;
}
#message.show {
visibility: visible;
-webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
/* The animation*/
@-webkit-keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@-webkit-keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
@keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
<button onclick="myFunction()">Copy</button>
<!-- This is the toast message -->
<div id="message">Text is copied!!</div>
Комментарии:
1. всегда используйте toast для отображения таких элементов