Clipboard.js循环按钮

时间:2018-10-13 16:55:56

标签: javascript twig clipboard.js

我使用剪贴板.js,单击我的一个按钮后,我想在该按钮下显示一条成功消息,但我无法遍历整个循环。

这是按钮:

<button type="button" class="clipboard-button button-rect" data-clipboard-text="{{ site.author.email|safe_email }}">
  <span class="button-text">Get in touch</span>
  <span class="clipboard-message">My E-Mail has been copied</span>
</button>

这是js:

var clipboard = new ClipboardJS('.clipboard-button');

clipboard.on('success', function () {
    var message = document.querySelectorAll('.clipboard-message');
    message.style.opacity = '1';
    setTimeout(function () {
        message.style.opacity = '0';
    }, 2000);
});

我想在按下的按钮下方显示消息,而不是每个按钮都显示。

感谢您的帮助,我做了很多尝试。我是JS初学者,所以请耐心等待。 :)

1 个答案:

答案 0 :(得分:0)

您应该看的是实现检索单击的DOM元素(在这种情况下为按钮)。这样就很容易找到对应的.clipboard-message span元素。

要检索被单击的元素,可以使用赋予success事件回调函数的参数,如此处所述:https://clipboardjs.com/#events

然后您的JavaScript代码变为:

var clipboard = new ClipboardJS('.clipboard-button');

clipboard.on('success', function (e) {
    // e.trigger corresponds to the clipboard-button DOM element that triggered the event
    // You can then use querySelector(...) to retrieve to first child element with the class clipboard-message
    var message = e.trigger.querySelector('.clipboard-message');
    message.style.opacity = '1';
    setTimeout(function () {
        message.style.opacity = '0';
    }, 2000);
});

这是一个工作代码段供您尝试:

var clipboard = new ClipboardJS('.clipboard-button');

clipboard.on('success', function (e) {
    var message = e.trigger.querySelector('.clipboard-message');
    message.style.opacity = '1';
    setTimeout(function () {
        message.style.opacity = '0';
    }, 2000);
});
.clipboard-message {
    color: green;
    opacity: 0;
}
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<button type="button" class="clipboard-button button-rect" data-clipboard-text="{{ site.author.email|safe_email }}">
  <span class="button-text">Get in touch</span>
  <span class="clipboard-message">My E-Mail has been copied</span>
</button>
<button type="button" class="clipboard-button button-rect" data-clipboard-text="{{ site.author.email|safe_email }}">
  <span class="button-text">Here is your ID</span>
  <span class="clipboard-message">My ID has been copied</span>
</button>