javascript - 将超链接从用户(文本)转换为图像

标签 javascript html image chat

当用户发表评论并且该评论中有图像链接(*.jpg 或 *.png)并且我想实时检查以使用 JavaScript 将该源设为图像标记时,我必须在 JavaScript 中做什么。我该如何进行这项检查?

最佳答案

您可以使用表达式来检查文件扩展名:

function checkURL(url) {
    return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
}

使用如下函数检查图像是否可以加载 URL:

function testImage(url, callback, timeout) {
    timeout = timeout || 5000;
    var timedOut = false, timer;
    var img = new Image();
    img.onerror = img.onabort = function() {
        if (!timedOut) {
            clearTimeout(timer);
            callback(url, "error");
        }
    };
    img.onload = function() {
        if (!timedOut) {
            clearTimeout(timer);
            callback(url, "success");
        }
    };
    img.src = url;
    timer = setTimeout(function() {
        timedOut = true;
        callback(url, "timeout");
    }, timeout); 
}

此函数将在将来的某个时间使用两个参数调用您的回调:原始 URL 和结果(“成功”、“错误”或“超时”)。

关于javascript - 将超链接从用户(文本)转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37250921/

相关文章:

javascript - 从 Promise 构造函数返回值

javascript - 如何在 jQuery 中隔离 div?

javascript - jquery 下一个 div 元素选择

c++ - OpenGL 纹理未正确环绕具有提供的 UV 坐标的对象

html - 当我找不到 <img> 标签时,如何从网站获取图片?

Android:显示可变图像

javascript - 突变观察者未移除。为什么? (795978错误)

javascript - 使用 jquery 发布粘性导航

jquery - HTML5, jQuery,... >> 平滑触摸兼容的拖放/输入范围 slider 解决方案有人吗?

html - 如何在 div 内的 span 内垂直居中 img?