1. 程式人生 > >HBuilder開發詞典app(四)--呼叫有道api完成翻譯功能

HBuilder開發詞典app(四)--呼叫有道api完成翻譯功能

這一節也比較簡單,就是建一個textarea獲取使用者輸入的值,然後呼叫有道api進行翻譯,最後展現在相應位置,需要注意的是,點選頭部的翻譯按鈕自動跳轉到翻譯頁面,並且底部欄點亮樣式會隨之改變:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"
/>
<title></title> <link href="css/mui.min.css" rel="stylesheet"/> </head> <body> <div class="mui-content"> <div style="width:90%; padding-top:38px; margin:0 auto;"> <textarea id="keywords" style="width:100%; height:128px;" placeholder="請輸入要翻譯的文字"
>
</textarea> </div> <div style="width:90%; margin:0 auto;"> <button type="button" id="submitBtn" class="mui-btn" style="width:100%;">開始翻譯</button> </div> <div style="width:90%; background:#FFFFFF; margin:0 auto; margin-top:18px; display:none;" id
="resShow">
<p style="line-height:1.8em; font-size:15px; padding:10px;"></p> </div> </div> <script src="js/mui.min.js"></script> <script src="js/h.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> mui.init(); var _index, _self, _next,_prev; h('#submitBtn').tap(function(){ var keywords = h('#keywords').val(); if(keywords.length < 1){mui.toast('請輸入要翻譯的文字'); return false;} mui.getJSON( 'http://fanyi.youdao.com/openapi.do?keyfrom=testorot&key=1145972070&type=data&doctype=json&version=1.1&q='+keywords, function(data){ console.log(JSON.stringify(data)); h('#resShow').find('p').html(data.translation); h('#resShow').show(); } ); }); mui.plusReady(function(){ _self = plus.webview.currentWebview(); _next = plus.webview.getWebviewById('sub3.html'); _prev = plus.webview.getWebviewById('sub1.html'); _index = plus.webview.getLaunchWebview(); //向右滑動 _self.drag({ direction : "left", moveMode : "followFinger" },{ view : _next, moveMode : "follow" },function(e){ if(e.type == 'end' && e.result){ _index.evalJS('h("#navFooter").find("a").removeClass("mui-active"); h("#nav3").addClass("mui-active")') } }); //向左滑動 _self.drag({ direction : "right", moveMode : "followFinger" },{ view : _prev, moveMode : "follow" },function(e){ if(e.type == 'end' && e.result){ _index.evalJS('h("#navFooter").find("a").removeClass("mui-active"); h("#nav1").addClass("mui-active")') } }); }); </script> </body> </html>

主要程式碼在這,還需要新增一些css樣式,已經加到mui.css尾部了,最後index.html裡需要做一個searchBut的觸發事件:


h('#searchBut').tap(function(){
    changSub(2);
    h('#navFooter').find("a").removeClass('mui-active');
    h('#nav2').addClass('mui-active');
});