
??想了解更多關(guān)于開源的內(nèi)容,請(qǐng)?jiān)L問:??
??51CTO 開源基礎(chǔ)軟件社區(qū)??
??https://ost.51cto.com??
前言
大家好呀!由于前段時(shí)間學(xué)業(yè)較忙,斷更了一段時(shí)間?,F(xiàn)在開啟續(xù)更!本文是關(guān)于web組件抽獎(jiǎng)案例(ArkTS)的學(xué)習(xí)筆記,漫漫學(xué)習(xí)路,留下筆記鞏固之余又便于溫故而知新~話不多說,以下是我這次的小分享??
概述
本文分享的案例是Web組件如何加載本地H5小程序。所加載的頁(yè)面是一個(gè)由HTML+CSS+JavaScript實(shí)現(xiàn)的完整小應(yīng)用。至于加載云端的H5小程序,實(shí)現(xiàn)步驟類似,可移步至??codelabs-Web組件抽獎(jiǎng)案例??細(xì)覽。
效果圖如下:

正文
關(guān)鍵知識(shí)概念
- ??Web組件?? :提供具有網(wǎng)頁(yè)顯示能力的Web組件。訪問在線網(wǎng)頁(yè)時(shí)需添加網(wǎng)絡(luò)權(quán)限:ohos.permission.INTERNET.
- runJavaScript:異步執(zhí)行JavaScript腳本,并通過回調(diào)方式返回腳本執(zhí)行的結(jié)果。runJavaScript需要在loadUrl完成后,比如onPageEnd中調(diào)用。
runJavaScript(options: { script: string, callback?: (result: string) => void }) - onConfirm:網(wǎng)頁(yè)調(diào)用confirm()告警時(shí)觸發(fā)此回調(diào)。此案例是用于回顯抽獎(jiǎng)結(jié)果。
onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
一、創(chuàng)建空項(xiàng)目
選擇HarmonyOS模板,項(xiàng)目SDK選擇為API9,選擇模型為Stage模型。
如果要加載云端H5小程序的話,要記得在module.json5文件下添加網(wǎng)絡(luò)權(quán)限:
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
],
二、編寫本地H5頁(yè)面
在src/main/resources/rawfile下分別創(chuàng)建:文件夾img用于存放抽獎(jiǎng)?wù)故镜膱D片資源;文件index.html用于編寫頁(yè)面布局;css文件夾下再創(chuàng)建文件index.css,用于編寫組件的樣式;js文件夾下再創(chuàng)建文件index.js,用于編寫抽獎(jiǎng)的函數(shù)處理。

主要代碼(抽獎(jiǎng)功能實(shí)現(xiàn)):
// 旋轉(zhuǎn)函數(shù)
function roll() {
// 速度衰減
speed -= 50;
if (speed <= 10) {
speed = 10;
}
// 每次調(diào)用都去掉全部active類名,即去掉選中單元格的效果
for (let j = 0; j < allPrizesLi.length; j++) {
allPrizesLi[j].classList.remove('active');
}
prizesPosition++;
// 計(jì)算轉(zhuǎn)圈次數(shù),每至尾元素則圈數(shù)+1
if (prizesPosition >= allPrizesLi.length - 1) {
prizesPosition = 0;
count++;
}
//為當(dāng)前選中的單元格添加active類,以添加選中的效果樣式
allPrizesLi[prizesPosition].classList.add('active');
let initSpeed = 500;
let timer; //定義定時(shí)器
let totalCount = 5; // 至少轉(zhuǎn)動(dòng)的總?cè)?shù)
// 滿足轉(zhuǎn)圈數(shù)和指定位置就停止
if (count >= totalCount && (prizesPosition + 1) == index) {
clearTimeout(timer);
isClick = true;
speed = initSpeed;
timer = setTimeout(openDialog, 1000); // 等待1s打開彈窗
} else {
timer = setTimeout(roll, speed); // 不滿足條件時(shí)調(diào)用定時(shí)器
// 最后一圈減速
if (count >= totalCount - 1 || speed <= 50) {
speed += 100;
}
}
}
// 抽獎(jiǎng)開始函數(shù)
function startDraw() {
// 防止抽獎(jiǎng)多次觸發(fā)
if (isClick) {
count = 0;
// 隨機(jī)產(chǎn)生中獎(jiǎng)位置
index = Math.floor(Math.random() * prizesArr.length + 1);
roll();
isClick = false;
}
}
function openDialog() {
confirm(prizesArr[prizesPosition]);
}
三、調(diào)用web組件
在pages文件下創(chuàng)建文件MainPage和WebPage,其中WebPage用于調(diào)用web組件,在MainPage中有用到一個(gè)自定義屬性,覺得蠻有用的,記錄一下:
@Extend(Button) function fancy (top: string) {
.fontSize(16)
.fontColor($r('app.color.start_window_background'))
.width('86.7%')
.height('5.1%')
.margin({ top: top })
.backgroundColor($r('app.color.blue'))
.borderRadius('20')
}
Navigator({ target:'pages/WebPage', type: NavigationType.Push }) {
Button($r('app.string.loadLocalH5'))
.fancy('10%')
}
.params({ path:$rawfile('index.html'), tips: $r('app.string.local') })
}
通過navigator組件帶參跳轉(zhuǎn)至WebPage界面,使用web組件前要先創(chuàng)建一個(gè)web控制器,則添加以下代碼。
其中,webviewController要將IDE升級(jí)到最新版本才能用,是API9+的接口,上述WebController接口在最新版本時(shí)棄用了。
webController: web_webview.WebviewController = new web_webview.WebviewController();
@State params: object = router.getParams();

同時(shí)要注意在EntryAbility.ts文件下修改:,也要注意查看main_pages.json的配置。

WebPage中主要代碼部分:
// web組件加載本地H5
Web({ src: this.params['path'], controller: this.webController })
.zoomAccess(false)
.width('93.3%')
.aspectRatio(1)
.margin({ left: '3.3%', right: '3.3%', top:'7.1%'})
.onConfirm((event) => {
AlertDialog.show({
message: '恭喜您抽中' + `${event.message}`,
confirm: {
value: $r('app.string.web_alert_dialog_button_value'),
action: () => {
event.result.handleConfirm();
}
},
cancel: () => {
event.result.handleCancel();
}
});
return true;
})
下方的按鈕,異步執(zhí)行JavaScript腳本startDraw()。
Button($r('app.string.btnValue'))
.fontSize(16)
.fontColor($r('app.color.start_window_background'))
.margin({ top: '10%' })
.width('86.7%')
.height('5.1%')
.backgroundColor($r('app.color.blue'))
.borderRadius('20')
.onClick(() => {
this.webController.runJavaScript('startDraw()');
})
到此,然后就可以運(yùn)行模擬器P50進(jìn)行調(diào)試了!
文章相關(guān)附件可以點(diǎn)擊下面的原文鏈接前往下載:
??https://ost.51cto.com/resource/2553??
??https://ost.51cto.com/resource/2556??
??想了解更多關(guān)于開源的內(nèi)容,請(qǐng)?jiān)L問:??
??51CTO 開源基礎(chǔ)軟件社區(qū)??
??https://ost.51cto.com??