访问者如何在剪贴板上复制内容时如何自定义警报

问题描述 投票:2回答:1

在访问者浏览器中的Web共享API方法无效时,如何自定义警报对话框。 This is a link Questions with the post.

<script>
var title = document.title;
var url = window.location.href;

document.querySelectorAll('.shareBtn').forEach(function (btn) {
    var text = btn.previousElementSibling.textContent + '\n';
    btn.addEventListener('click', function () {
        if (navigator.share) {
            navigator.share({
                title: title,
                text: text,
                url: url
            });
        }else{
                var shareText = document.createElement('textarea');
                document.body.appendChild(shareText)
                shareText.value = text+url;
                shareText.select();
                document.execCommand('copy',false);
                shareText.remove();
                alert(" Text Copied");
            }
    });
});
</script>

我想创建类似于大多数android应用程序的用法,以在复制任何文本后立即显示通知,而文本会在一秒钟后自动消失。

enter image description here

并且当Web浏览器不支持Web Share API方法时,有任何方法可以将按钮文本从“单击共享”自动更改为“单击复制”

<button id="shareBtn">Click to Share</button>
javascript share blogger android-sharing
1个回答
0
投票

您可以创建具有所需样式的隐藏元素,并在复制1秒钟后显示它

HTML

<div class="alert-msg">Text Copied</div>

CSS

.alert-msg {
    position: fixed;
    padding: 10px 50px;
    border-radius: 4px;
    background-color: black;
    color: white;
    z-index: 1000;
    top: 50%;
    left: 50%;
    display: none;
}

JS

<script>
var title = document.title;
var url = window.location.href;
var msgDiv = document.querySelector('.alert-msg');

document.querySelectorAll('.shareBtn').forEach(function (btn) {
    var text = btn.previousElementSibling.textContent + '\n';
    btn.addEventListener('click', function () {
        if (navigator.share) {
            navigator.share({
                title: title,
                text: text,
                url: url
            });
        } else {
                var shareText = document.createElement('textarea');
                document.body.appendChild(shareText)
                shareText.value = text+url;
                shareText.select();
                document.execCommand('copy',false);
                shareText.remove();
                msgDiv.style.display = 'block';
                setTimeout(function () { msgDiv.style.display = 'none'; }, 1000);
            }
    });
});
</script>
© www.soinside.com 2019 - 2024. All rights reserved.