用到的資源:https://download.csdn.net/download/impossible1994727/12474244
假設我們遇到的需求爲:選中網頁的某段文字後彈出小彈窗,出現複製按鈕,並且可以提示覆製成功。
代碼如下:
<style>
.btn {
position: absolute;
display: none;
}
</style>
<div style="position: relative;" class="fa">
<button class="btn">
<span class="aaa">複製</span>
</button>
<div class="context">
散文是一個漢語詞彙,拼音是sǎn wén。一指文采煥發;二指猶行文;三指文體名。</div>
</div>
<script>
var txt;
$('.context').mouseup(function (e) {
txt = window.getSelection ? window.getSelection() : document.selection.createRange().text;
txt = txt.toString();
$('.btn').css({
'margin-top': e.clientY,
"margin-left": e.screenX,
"display": 'block'
})
})
//複製功能
var clipboard = new Clipboard('.aaa', {
text: function () {
return txt;
}
});
clipboard.on('success', function (e) {
alert('複製成功:' + e.text)
$('.btn').hide();
});
clipboard.on('error', function (e) {
console.log(e);
});
</script>