JavaScript实现划词翻译

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetWord.aspx.cs" Inherits="Pro.GetWord" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="Content/htrans.css" rel="stylesheet" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <span onclick="SelectText()">河中鱼类离奇死亡,下游居民频染怪病,沿岸植物不断变异,是残留农药?还是生化攻击?》</span>

        </div>
    </form>
    <script src="http://shared.ydstatic.com/js/jquery/jquery-3.1.1.min.js"></script>
    <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.js"></script>
    <script src="js/htrans.js"></script>
    <script type="text/javascript">
        function SelectText()
        {
            try
            {
                var selecter = window.getSelection().toString();
                if (selecter != null && selecter.trim() != "")
                {
                    //alert(selecter);
                }
            } catch (err)
            {
                var selecter = document.selection.createRange();
                var s = selecter.text;
                if (s != null && s.trim() != "")
                {
                    ///alert(s)
                }
            }
        }
        //替换文本前与后的空格
        String.prototype.trim = function ()
        {
            return this.replace(/(^\s*)|(\s*$)/g, "");
        }
         

        $("body").htrans({
            "appId": "14a2****************",
            "secretKey": "dEdzze***********WHx1Q"
        });
    </script>
</body>
</html>

htrans.js

(function ($) {
    $.fn.extend({
        "htrans": function (options) {
            options = $.extend({
                "apiUrl": "https://openapi.youdao.com/api",
                "appId": "",
                "secretKey": "",
                "from": "zh-CHS",
                "to": "en"

            }, options);

            $('body').append('<div class="htrans-tip-box"></div>');

            var $this = $(this);
            var l = t = browserWidth = 0;
            var tip = $(".htrans-tip-box");

            //鼠标抬起进,获取选择文字的字数。并根据字数,是否显示弹出层
            $this.mouseup(function (event) {
                //IE和火狐兼容性的处理函数。
                function htrans() {
                    if (document.selection) {
                        return document.selection.createRange().text;// IE
                    } else {
                        return window.getSelection().toString(); //标准
                    }
                }

                var q = htrans();
                if (q.length <= 0) {
                    return;
                }

                l = event.clientX;
                t = event.clientY;
                browserWidth = document.body.clientWidth;

                result = getTranslate(q);
            });

            // 获取翻译内容
            var getTranslate = function(q) {
                var salt = (new Date).getTime();
                var sign = md5(options.appId + q + salt + options.secretKey);

                $.ajax({
                    url: options.apiUrl,
                    type: 'post',
                    async: false,
                    dataType: 'jsonp',
                    data: {
                        q: q,
                        appKey: options.appId,
                        salt: salt,
                        from: options.from,
                        to: options.to,
                        sign: sign
                    },
                    success: function (data) {
                        display(translateBox(q, data));
                    },
                    fail:function() {
                        display("获取数据失败~")
                    }
                })
            };

            // 显示提示框,用以显示翻译信息或提示信息
            var display = function(text) {
                var tipWidth = tip.outerWidth();
                var leftPos = 0;

                if (browserWidth - l > tipWidth) {
                    leftPos = l + 10;
                } else {
                    leftPos = l - tipWidth;
                }
                tip.html(text)
                    .css({"top": t + 10, "left": leftPos})
                    .fadeIn();
            };

            var translateBox = function(q, result) {
                if (parseInt(result.errorCode)) {
                    return "请求错误,错误码:" + result.errorCode;
                }

                var content = phonetic = '';
                if (result.basic !== undefined) {
                    var explains = result.basic.explains;
                    var phonetic = getPhonetic(result.basic);
                    var i;

                    for (i = 0; i < explains.length; i++) {
                        var line = explains[i].replace(/^(\w+\.)/g, '<span class="htrans-tip-preposition">$1</span>');
                        content += (i + 1) + ". </span>" + line + "<br />";
                    }
                } else if (result.translation !== undefined) {
                    for (i = 0; i < result.translation.length; i++) {
                        content += (i + 1) + ". " + result.translation[i] + "<br />";
                    }
                } else {
                    return "无翻译结果。";
                }

                var title = '<span class="htrans-tip-query-word">' + q + '</span> ';

                if (phonetic) {
                    title += '<span class="htrans-tip-phonetic">[' + phonetic + "]</span><br />";
                } else {
                    title += "<br />";
                }

                return title + '<div class="htrans-tip-content">' + content + '</div>';
            };

            // 获取单词拼音
            var getPhonetic = function(basic) {
                var phonetic = [
                    basic['phonetic'],
                    basic["uk-phonetic"],
                    basic["uk-phonetic"]
                ];

                // 去除空值
                phonetic.filter(function (n) {
                    return n;
                });

                return phonetic ? phonetic[0] : '';
            };

            // 点击文档任何位置,翻译框消失
            $(document).on("click", function () {
                tip.fadeOut();
            });

            // 改变浏览器尺寸时,翻译框消失
            $(window).resize(function () {
                tip.fadeOut();
            });

            // 阻止冒泡,防止第一次选中文字时,由于冒泡,
            // 而触发了$(document).click事件
            tip.on("click", function (event) {
                event.stopPropagation();
            });

            return $this;
        }
    })
})(jQuery);

htrans.css

.htrans-tip-box {
    border: 1px solid #cfcfcf;
    border-radius: 3px;
    padding: 15px 22px;
    position: fixed;
    min-width: 300px;
    max-width: 350px;
    width: auto;
    height: auto;
    min-height: 100px;
    background: #efefef;
    display: none;
    line-height: 1.5em;
}

.htrans-tip-query-word {
    color: black;
    font-weight: 700;
}

.htrans-tip-phonetic {
    color: #5fa207;
}

.htrans-tip-content {
    font-size: 85%;
}

.htrans-tip-preposition {
    color: #7a7a7a;
}

如图

在这里插入图片描述在这里插入图片描述

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值