翻译功能的实现:
.wxml:
<!--pages/top1.wxml--> <!-- 翻译功能 --> <view></view> <view class="head"> <rich-text> </rich-text> </view> <view class="t_c"> <view class="text"> <text class="info">请输入翻译内容:</text> <!-- 输入的时候就会触发inputInfo函数,{{text}}里的text对应js的data中的text --> <textarea class="my_input" rows="8" value="{{text}}" bindinput="inputInfo"></textarea> <view class="action"> <!-- bindtap里的函数在点击对应图片时被调用 点“译”调用search函数,del函数同理(调用时清空翻译内容和翻译结构) --> <image class="search" src="http://s5lwjq2lp.hn-bkt.clouddn.com/%E8%8B%B1%E6%96%87%E7%BF%BB%E8%AF%91.png" bindtap="search"></image> <image class="del" bindtap="del" src="http://s5lwjq2lp.hn-bkt.clouddn.com/%E5%88%A0%E9%99%A4%20%283%29.png"></image> </view> </view> <view class="tran_text"> <text class="info">翻译结果:</text> <textarea class="tran_content" rows="8" value="{{translation}}"></textarea> </view> </view>
.wxss:
/* pages/top1.wxss */ Page{ background-color: #CCFF99; } .head{ font-size: 42rpx; text-align: center; background-color: #66CCCC; padding: 10rpx; color: #fff; } .info{ color: #000000; margin-left:3%; margin-bottom: 10rpx; margin-top: 10%; font-size:3vh; font-family: Georgia, 'Times New Roman', Times, serif; } .text{ width: auto; height: 530rpx; display: flex; justify-content: flex-start; flex-wrap: wrap; border-bottom: 10vh solid #CCFF99; margin-left: 3%; margin-right: 3%; } .my_input{ width: 100%; height: 350rpx; margin-left: 1rpx; margin-right: 1rpx; margin-bottom: 15rpx; background-color: white; border: 2rpx solid #292421; border-radius: 4%; color: #292421; } .action{ width: 100%; height: 28rpx; display: flex; margin: 15px; justify-content:space-between; align-items: center; background-color: #CCFF99; } .search{ width: 64rpx; height: 64rpx; } .del{ width: 64rpx; height: 64rpx; } .tran_text{ height: 480rpx; display: flex; justify-content: flex-start; flex-wrap: wrap; margin-left: 4%; margin-right: 4%; } .tran_content{ width: 100%; height: 390rpx; margin-left: 1rpx; margin-right: 1rpx; background-color: white; border: 2rpx solid #292421; border-radius: 4%; }
.json:
{ "usingComponents": {}, "navigationBarTitleText":" 中英翻译", "navigationBarBackgroundColor": "#66CCCC" }
.js:
Page({ data: { token:'24.5f26605794878019027e80bda475ea26.2592000.1704990882.282335-44855856', text: "请输入需要翻译的中文内容", translation: "", }, del(){ this.setData({ text:'', translation:'' }) }, // 调用翻译的文档里有 search(){ console.log(this.data.text); wx.request({ url: 'https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=' +this.data.token, data:{ 'from':'zh', 'to':'en', 'q':this.data.text }, header:{ 'Content-Type': 'application/json;charset=utf-8' }, method:'POST', success: (res)=>{ let result = res.data.result.trans_result[0].dst this.setData({ translation:result }) }, fail:(err)=>{ console.log(err); } }) }, // 获取要翻译的内容 inputInfo(e){ this.setData({ text:e.detail.value, }) }, })
实现的界面: