Скопируйте текст по клику и затем отобразите небольшое всплывающее окно - расширение кода - PullRequest
0 голосов
/ 04 мая 2019

Мне нужен небольшой скрипт, который позволит мне копировать текстовую строку при нажатии без кнопки .

Я нашел этот код:

function copy(that){
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
inp.remove();
}

Код копирует текст по клику, но не показывает никакого сообщения. Я хотел бы немного изменить его, чтобы при нажатии пользователем на текст он копировался и показывал небольшое всплывающее сообщение в течение 2-3 (затем оно должно исчезнуть само собой) секунд, говоря, что текст был скопирован в буфер обмена. У кого-нибудь есть идеи, как изменить код таким образом?

<p onclick="copy(this)">example text</p> - так он распознает, какой код копировать.

Ответы [ 3 ]

0 голосов
/ 04 мая 2019

Эй, есть полный пример:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <input type="text" onclick="copy(this)" value="malek gorchene"></input>
    <!-- this p is for the notification -->
    <p></p>

</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script type="text/javascript">


    function copy(elem){
        input  = $(elem).val();
        elem.select();//Select the text in the input element 
        document.execCommand('copy');//copy it 

        $(elem).next().text('text copied');

        setTimeout(function(){$(elem).next().text('');}, 2000);//
    }


</script>
</html>
0 голосов
/ 04 мая 2019

Привет, вот и первый вопрос, а второго нет:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <input type="text" onclick="copy(this)" value="malek gorchene"></input>
    <p></p>
    <p onclick="copy(this)">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    <!-- this p is for the notification -->
    <p></p>

</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script type="text/javascript">


    function copy(elem){
        if($(elem).text()){
            var dummy = document.createElement("textarea");
            document.body.appendChild(dummy);
            dummy.value = $(elem).text();
            dummy.select();
            document.execCommand("copy");
            document.body.removeChild(dummy);
        }else{
            input  = $(elem).val();
            elem.select();//Select the text in the input element 
            document.execCommand('copy');//copy it 
        }



        $(elem).next().text('text copied');

        setTimeout(function(){$(elem).next().text('');}, 2000);//
    }


</script>
</html>
0 голосов
/ 04 мая 2019

Я надеюсь, что эта функция поможет вам:

copy(){
input  = $(this).val();
document.execCommand('copy',false,input);

$(this).next('text copied');

setTimeout(function(){$(this).next().remove();}, 2000);
}

Помните, что вы должны создать тег, где вы будете отображать сообщение рядом с тегом ввода

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...