Dar*_*ski 4 javascript clipboard jquery zeroclipboard clipboard.js
点击后.fw-code-copy-button我想从它最近的容器中复制源代码.
.fw-code-copy-button用户单击专用的"查看源"按钮后动态创建-s.
例如Html按钮:
<span class="fw-code-copy">
<span class="fw-code-copy-button" data-clipboard-text="...">copy</span>
</span>
Run Code Online (Sandbox Code Playgroud)
这是我触发click事件的方法,并定义要复制到剪贴板的源代码:
$(document).on("click", ".fw-code-copy-button", function(){
var source = $(this).closest(".fw-code-copy").next("code").text();
});
Run Code Online (Sandbox Code Playgroud)
这就是clipboard.js触发它的复制事件的方式
new Clipboard(".fw-code-copy-button", {
text: function(trigger) {
return source; // source should somehow be copied from scope above it
}
});
Run Code Online (Sandbox Code Playgroud)
每当我点击网站上的任何地方时,都会出现以下错误:
Uncaught Error: Missing required attributes, use either "target" or "text"
Run Code Online (Sandbox Code Playgroud)
但首先,我不想定义要复制的文本data-clipboard-text="..."
,其次data-clipboard-text是使用"..."它的值来定义.
如果有人愿意支付一秒钟,我将非常感激.
[编辑]我已经编写了jsFiddle用于演示,并且令人惊讶的是UncaughtError消失了,但我仍然需要将source代码从onClick 移动到剪贴板范围.
根据您的原始代码:
new Clipboard(".fw-code-copy-button", {
text: function(trigger) {
return $(trigger).closest(".fw-code-copy").next("code").text();
}
});
Run Code Online (Sandbox Code Playgroud)
触发器是您单击的按钮.获取父级,然后返回代码块内的文本.您还需要修剪任何前导和尾随空白区域.
这将在代码块中抓取文本,如您所包含的示例中所示
new Clipboard(".fw-code-copy-button", {
text: function(trigger) {
return $(trigger).parent().find('code').first().text().trim();
}
});Run Code Online (Sandbox Code Playgroud)
.fw-code-copy {
display: block;
position: relative;
width: 400px;
height: 30px;
background: #FFE;
border: thin solid #FF0;
margin-bottom: 0.5em;
padding: 0.5em;
}
.fw-code-copy-button {
position: absolute;
top: 8px;
right: 8px;
padding: 0.25em;
border: thin solid #777;
background: #800080;
color: #FFF;
}
.fw-code-copy-button:hover {
border: thin solid #DDD;
background: #992699;
cursor: pointer;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.3/clipboard.min.js"></script>
<span class="fw-code-copy">
<span class="fw-code-copy-button">Copy</span>
<code><link rel="stylesheet" href="style-1.css"></code>
</span>
<span class="fw-code-copy">
<span class="fw-code-copy-button">Copy</span>
<code><link rel="stylesheet" href="style-2.css"></code>
</span>
<span class="fw-code-copy">
<span class="fw-code-copy-button">Copy</span>
<code><link rel="stylesheet" href="style-3.css"></code>
</span>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8964 次 |
| 最近记录: |