让访客可以在 Typecho 评论贴图(Typecho 评论插图功能实现)

让访客可以在 Typecho 评论贴图(Typecho 评论插图功能实现)

chen'mo
2023-04-08 / 2 评论 / 8,167 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年04月15日,已超过371天没有更新,若内容或图片失效,请留言反馈。

在 Typecho 评论的内容中,如果用 <img src="图片地址" />的语法,将被 Typecho 自带的过滤器删除,所以评论后看不到贴图。

接触贴图限制

我们需要手动打开限制,这个一般推荐在themeInit函数里强制设置,这样对用户来说就无需额外操作。

修改functions.php

function themeInit($archive) {
   $options = Helper::options();
   //允许图片标签
   $options->commentsHTMLTagAllowed .= '<img class="" src="" data-src="" alt="" style=""/>';
}

这样我们就可以在评论区通过
<img src="图片地址" />
的语法来贴图了。

支持使用短代码格式贴图

使用短代码的格式贴图

[img src="图片地址"]

好处是有别的html过滤器也不怕图片被过滤掉了。

处理评论内用需要用到钩子,往functions.php

加入以下代码。

Typecho_Plugin::factory('Widget_Abstract_Comments')->contentEx = ['CommensHelper', 'parse'];
class CommensHelper
{
    public static function parse(string $content, $archive, ?string $lastResult) :string 
    {
        if ($lastResult) $content = $lastResult;
        // 判断是不是在文章页
        $isSingle = Typecho_Widget::widget('Widget_Archive')->is('single');
        if ($isSingle) {
            $content = preg_replace_callback('/\[img=?\]*(.*?)(\[\/img)?\]/ism', function ($matches) {
            return sprintf('', Typecho_Common::safeUrl($matches[1]));
            }, $content);
        } else {
            $content = preg_replace('/\[img=?\]*(.*?)(\[\/img)?\]/ism', _t("[图片]"), $content);
        }
        return $content;
    }
}

评论框增加一个按钮用于插入图片

修改comments.php,在合适位置加入以下代码:

<a id="insert-image" href="javascript:void(0)" data-textarea="textarea[name='text']" data-prompt-text="请输入图片链接">插入图片</a>
<script>
    let el = document.getElementById('insert-image');
    el.addEventListener('click', (event) => comment_image.apply(el, [event, document.querySelector(el.dataset.textarea)]), false);

    function comment_image(event, textarea) {
        var URL = prompt(this.getAttribute("data-prompt-text") || "");
        if (URL) {
            replaceSelectedText(textarea, '[img]' + URL + '[/img]');
        }
        return false;
    }

    function getInputSelection(el) {
        var start = 0, end = 0, normalizedValue, range,
            textInputRange, len, endRange;

        if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
            start = el.selectionStart;
            end = el.selectionEnd;
        } else {
            range = document.selection.createRange();

            if (range && range.parentElement() == el) {
                len = el.value.length;
                normalizedValue = el.value.replace(/\r\n/g, "\n");

                // Create a working TextRange that lives only in the input
                textInputRange = el.createTextRange();
                textInputRange.moveToBookmark(range.getBookmark());

                // Check if the start and end of the selection are at the very end
                // of the input, since moveStart/moveEnd doesn't return what we want
                // in those cases
                endRange = el.createTextRange();
                endRange.collapse(false);

                if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                    start = end = len;
                } else {
                    start = -textInputRange.moveStart("character", -len);
                    start += normalizedValue.slice(0, start).split("\n").length - 1;

                    if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                        end = len;
                    } else {
                        end = -textInputRange.moveEnd("character", -len);
                        end += normalizedValue.slice(0, end).split("\n").length - 1;
                    }
                }
            }
        }

        return {
            start: start,
            end: end
        };
    }

    function replaceSelectedText(el, text) {
        var sel = getInputSelection(el), val = el.value;
        el.value = val.slice(0, sel.start) + text + val.slice(sel.end);
    }
</script>

JS代码积分下载:

积分下载
子比go外链修改
« 上一篇 04-07
适用于Typecho的那年今日代码
下一篇 » 04-14

评论 (2)

插入图片
  1. 头像
    小魏先生 Lv.1   上海市上海市
    Windows 11 · Google Chrome
    沙发

    public static funtion parse(string $content, $archive, ?string $lastResult) :string

    这段代码报错

    回复
    1. 头像
      chen'mo 作者 Lv.5   湖南省娄底市
      Windows 11 · Google Chrome
      @ 小魏先生

      funtion打错了 应该是function

      回复