如何创建像Stack Overflow这样的可视差异视图呢?

时间:2012-08-15 06:18:15

标签: javascript version-control

Stack Overflow的差异视图非常好。我想用javascript做这件事,但我不知道如何开始,谁可以提出一些建议?

如下: StackOverflow's diff view

2 个答案:

答案 0 :(得分:10)

您可以尝试google-diff-match-patch项目,该项目提供强大的算法来执行同步纯文本所需的操作。

演示:http://jsfiddle.net/N6bAn/

代码:

<div class="test">
    <div id="oldStr" class="text">the stackoverflow question and answer version control is very well,i want to do this use javascript,but i don't know how to start,who can give some suggestion?thanks</div>
    <div id="newStr" class="text">Stack Overflow's diff view is very good. I want to do this using  javascript,but i don't know how to start,who can give some suggestion?thanks</div>
</div>
<input type="button" value="GO" onclick="launch()" />
<div class="test">
    <div class="text" id="outputOldStr"></div>
    <div class="text" id="outputNewStr"></div>
</div>
<script type="text/javascript">
    var dmp = new diff_match_patch();

    function launch() {
        var text1 = document.getElementById('oldStr').innerHTML;
        var text2 = document.getElementById('newStr').innerHTML;
        dmp.Diff_EditCost = 8;

        var d = dmp.diff_main(text1, text2);
        dmp.diff_cleanupEfficiency(d);
        var oldStr = "", newStr = "";
        for (var i = 0, j = d.length; i < j; i++) {
            var arr=d[i];
            if (arr[0] == 0) {
                oldStr += arr[1];
                newStr += arr[1];
            } else if (arr[0] == -1) {
                oldStr += "<span class='text-del'>" + arr[1] + "</span>";
            } else {
                newStr += "<span class='text-add'>" + arr[1] + "</span>";
            }
        }
        document.getElementById('outputOldStr').innerHTML = oldStr;
        document.getElementById('outputNewStr').innerHTML = newStr;
    }
</script>

答案 1 :(得分:4)

有一些JavaScript库可以进行差异可视化。这些是我发现的一些例子:

我没有尝试过任何一个,所以很遗憾我无法告诉你哪个最适合你的需要,但是值得一试。

<强>更新

jsdifflib看起来很有前途,你可以尝试a demo