JS的一些自定义函数(图片转base64、笛卡尔积、copy文本、文本框选中)

JS的一些自定义函数(图片转base64、笛卡尔积、copy文本、文本框选中)

Tony哥
2022-02-11 / 0 评论 / 125 阅读 / 正在检测是否收录...

以下是以往用过的一些简单方法,供大家参考一下:

/**
 * 文本框选中文字逻辑
 * @param object        textBox textarea 对象
 * @param int|string    start 选择开始索引或被选中文字的字符串
 * @param int|null      end
 */
function textareaSelect(textBox, start, end) {
    if (typeof textBox != 'object') {
        console.log('textareaSelect方法第一个参数应该为textarea对象');
        return;
    }
    if (textBox instanceof jQuery) textBox = textBox[0];
    if (!end) {
        let i = textBox.value.indexOf('' + start);
        end = i + ('' + start).length;
        start = i;
    }
    if (textBox.setSelectionRange) {
        textBox.setSelectionRange(start, end);
    } else if (textBox.createTextRange) {
        var rang = textBox.createTextRange();
        rang.collapse(true);
        rang.moveStart('character', start);
        rang.moveEnd('character', end - start);
        rang.select();
    }
    textBox.focus();
}


/**
 * 转base64图片
 * @param imgUrl 图片路径
 * @param w 调整宽 仅填写一个参数为等比例缩放
 * @param h 调整高 仅填写一个参数为等比例缩放
 * @param callback 回调 错误返回false及错误码
 */
function toBase64(imgUrl, callback, w, h) {
    if (!imgUrl) callback(false, '图片路径不存在或类型问题');
    let image = new Image();
    image.crossOrigin = '';
    image.referrerPolicy = "no-referrer";
    image.rel = "noreferrer";
    image.src = imgUrl;
    image.onload = function () {
        if (!w && !h) {
            w = 0;
            h = 0;
        } else if (!(w && h))
            if (w)
                h = image.height * (w / image.width);
            else
                w = image.width * (h / image.height);
        let c = document.createElement("canvas");
        c.width = w ? w : image.width;
        c.height = h ? h : image.height;
        let ctx = c.getContext("2d");
        ctx.drawImage(image, 0, 0, c.width, c.height);
        callback(canvas.toDataURL());
    };
}

/**
 * 笛卡尔积算法
 * 传入数组集合,如cartesianProductOf(...[[1,2],[3,4]])
 * @returns {T | (function(*=, *): Array)}
 */
function cartesianProductOf() {
    return Array.prototype.reduce.call(arguments, function (a, b) {
        let ret = [];
        a.forEach(function (a) {
            b.forEach(function (b) {
                ret.push(a.concat([b]));
            });
        });
        return ret;
    }, [[]]);
}

/**
 * copy文本内容
 * @param value
 */
function copy(value) {
    let cpInput = document.createElement("input");
    cpInput.setAttribute("id", "cp_input");
    cpInput.setAttribute("type", "text");
    cpInput.style.position = "absolute";
    cpInput.style.top = "-500px";
    cpInput.style.left = "-100px";
    cpInput.value = value;
    document.body.appendChild(cpInput);
    document.getElementById("cp_input").select();
    document.execCommand("copy");
    document.getElementById('cp_input').remove();
}
0

评论 (0)

取消