准备工作 去百度翻译api 申请通用 appid (有次数限制,非免费api)
下载js-sdk
本身 js-sdk本身没有支持网页翻译 ,原文作者 取网页中每个标签的文本内容 遍历翻译
demo如下
<script src="./js/jquery-3.2.1.min.js"></script>
<script src="./md5.js"></script>
<script type="text/javascript">
function GetBaidu(query,obj){
var q=query;
var appid = "20180102000111197";
var key = "jWla7SLM0EBHs9Bnmt67";
var salt = (new Date).getTime();
var str1 = appid + q + salt +key;
var sign = MD5(str1);
$.ajax({
url:'http://api.fanyi.baidu.com/api/trans/vip/translate',
type:'post',
dataType:'jsonp',
data:{
q:q,
from:'auto',
to:'en',
appid:appid,
salt:salt,
sign:sign
},
success:function(msg){
var html = "";
for(var i=0;i<msg.trans_result.length;i++){
console.log(msg.trans_result[i].dst);
html+=msg.trans_result[i].dst
}
obj.html(html)
}
});
}
var text = $('.main p').html(function(i,text){
//console.log(i+text);
GetBaidu(text,$(this));
});
var text = $('.main div').html(function(i,text){
//console.log(i+text);
GetBaidu(text,$(this));
});
var text = $('.main h2').html(function(i,text){
//console.log(i+text);
GetBaidu(text,$(this));
});
var text = $('.main span').html(function(i,text){
//console.log(i+text);
GetBaidu(text,$(this));
});
//console.log(text)
</script>
---------------------