标签归档:javascript

js复制文本到剪贴板

https://developer.mozilla.org/zh-CN/docs/Web/API/Clipboard/writeText


    function copyText(text) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(
                function () {
                    /* clipboard successfully set */
                },
                function () {
                    /* clipboard write failed */
                },
            );
        } else {
            let oInput = document.createElement('input');
            oInput.value = text;
            document.body.appendChild(oInput);
            oInput.select();
            document.execCommand("Copy");
            oInput.className = 'oInput';
            oInput.style.display = 'none';
        }
    }

    function oCopy(text) {
        copyText(text)
        layer.msg('复制成功!')
    }

js 批量打包下载图片一例

<script src="./js/jszip.min.js"></script>
<script src="./js/FileSaver.min.js"></script>
<script src="./jquery/2.1.3/js/jquery.min.js"></script>
<script>
    var zip = new JSZip();
    zip.file("Hello.txt", "Hello World\n");
    var img = zip.folder("images");
    img.file("1.png", getBase64("https://www.baidu.com/img/bd_logo1.png"), {base64: true});
    zip.generateAsync({type: "blob"})
        .then(function (content) {
            // see FileSaver.js
            saveAs(content, "example.zip");
        });


    //传入图片路径,返回base64
    function getBase64(img) {
        function getBase64Image(img, width, height) {//width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
            var canvas = document.createElement("canvas");
            canvas.width = width ? width : img.width;
            canvas.height = height ? height : img.height;

            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            var dataURL = canvas.toDataURL();
            var arr = dataURL.split(",");
            return arr[1];
        }

        var image = new Image();
        image.crossOrigin = 'Anonymous';
        image.src = img;
        var deferred = $.Deferred();
        if (img) {
            image.onload = function () {
                deferred.resolve(getBase64Image(image));//将base64传给done上传处理
            }
            return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
        }
    }
</script>

$.getScript原生实现

var script = document.createElement(‘script’);
script.type = ‘text/javascript’;
script.src = ‘/xxx.js’; //填自己的js路径
document.body.appendChild(script);// 缺点:不能跨域load

# 方法2

(function(){
var i = document.createElement(‘iframe’);
i.style.display = ‘none’;
// i.onload = function() {i.parentNode.removeChild(i);};
// i.name=”;
i.src = ‘http://xxx/xx’;
document.body.appendChild(i);
// i.contentWindow.document.body.innerHTML = ”;
})();