Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a visual diff view like Stack Overflow does?

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?

such as: StackOverflow's diff view

like image 877
artwl Avatar asked Aug 15 '12 06:08

artwl


1 Answers

you can try google-diff-match-patch project ,this project offer robust algorithms to perform the operations required for synchronizing plain text.

Demo:http://jsfiddle.net/N6bAn/

Code:

<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>
like image 110
programmer Avatar answered Sep 28 '22 01:09

programmer