JSFiddle - React, Tailwind, and code Playground

by Fooleap Chen

HTML

那一天,我在街上看到了条狗<a href="https://zh.wikipedia.org/wiki/狗" title="狗 - 维基百科">[1]</a>,后来发现居然是只狼<a href="https://zh.wikipedia.org/wiki/狼" title="狼 - 维基百科">[2]</a>。

<h2>参考资料</h2>

<ol id="refs"></ol>

CSS

a {
    text-decoration: none;
    color: blue;
    outline: none;
}
a[target="_blank"]:after {
    content:'↗';
}

JavaScript

var extLinks = document.querySelectorAll('a');
for (var i = 0; i < extLinks.length; i++) {
    // 选择非本站链接
    if (extLinks[i].hostname != location.hostname && /^javascript/.test(extLinks[i].href) == false) {
        // 去掉所选链接文本的最前、最后字符
        var numText = extLinks[i].innerHTML;
        var num = numText.substring(1, numText.length - 1);
        // 判断是否为数字
        if (!isNaN(num) && num) {
            var note = 'note-' + num;
            var ref = 'ref-' + num;
            var noteTitle = extLinks[i].getAttribute('title');
            var noteHref = extLinks[i].getAttribute('href');
            extLinks[i].setAttribute('href', '#' + note);
            extLinks[i].setAttribute('id', ref);
            extLinks[i].setAttribute('class', 'ref');
            extLinks[i].outerHTML = '<sup>' + extLinks[i].outerHTML + '</sup>';
            document.getElementById('refs').insertAdjacentHTML('beforeend', '<li class="note"><a href="#' + ref + '">&and;</a> <a href="' + noteHref + '" title="' + noteTitle + '" id="' + note + '" class="exf-text" target="_blank">' + noteTitle + '</a></li>');
        } else {
            // 不是数字保留并加上 target 属性
            extLinks[i].setAttribute('target', '_blank');
        };
    }
}

// 选择相关链接,使用正则匹配
var noteLinks = document.querySelectorAll('a[href^="#note"], a[href^="#ref"]');

function linkFocus() {
    // 清除背景颜色
    for (var i = 0; i < noteLinks.length; i++) {
        noteLinks[i].parentElement.style.backgroundColor = '';
    }
    // 高亮目标背景
    var href = this.href.split('#')[1];
    document.getElementById(href).parentElement.style.backgroundColor = 'rgb(235, 235, 235)';
}
for (var i = 0; i < noteLinks.length; i++) {
    if (noteLinks[i].addEventListener) {
        noteLinks[i].addEventListener('click', linkFocus, false);
    } else {
        noteLinks[i].onclick = linkFocus;
    }
}