HarmonyOS鸿蒙Next中如何修改web资讯页字体大小

HarmonyOS鸿蒙Next中如何修改web资讯页字体大小 web资讯页,点击设置字体,弹出窗动态调整字体大小

3 回复

实现方法:

1、使用分段空间 Segment 作为字号选择组件

2、通过设置web的 textZoomRatio 属性调整字体大小。

其他方案,通过runJavaScript 执行js代码,修改document.body.style。

const jsCode = `
  document.body.style.transform = 'scale(${scale})';
  document.body.style.transformOrigin = '0 0';
  document.body.style.width = 'calc(100% / ${scale})';
  `
this.controller.runJavaScript(jsCode)

预览效果:

cke_10041.gif

完整的demo:

/**
 * @fileName : WebFont.ets
 * @author : @cxy
 * @date : 2025/12/20
 * @description : 修改web资讯页字体大小
 */
import { webview } from "@kit.ArkWeb"
import { ItemRestriction, SegmentButton, SegmentButtonOptions, SegmentButtonTextItem } from "@kit.ArkUI";

@Component
export struct WebFont {
  @State isShowPopup: boolean = false
  @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
    buttons: [{ text: '小号' }, { text: '中号' }, { text: '大号' },
      { text: '超大号' }] as ItemRestriction<SegmentButtonTextItem>,
    backgroundBlurStyle: BlurStyle.BACKGROUND_THICK
  });
  @State @Watch('onSegmentButtonChange') tabSelectedIndexes: number[] = [1];
  @State textZoomRatio: number = 100
  private controller: WebviewController = new webview.WebviewController()
  private fontScaleList: number[] = [80, 100, 120, 140]

  aboutToAppear(): void {
    webview.WebviewController.setWebDebuggingAccess(true)
  }

  onSegmentButtonChange() {
    const index = this.tabSelectedIndexes[0]
    const scale = this.fontScaleList[index] as number
    this.textZoomRatio = scale

    // 另一种方案
    // const jsCode = `
    //   document.body.style.transform = 'scale(${scale})';
    //   document.body.style.transformOrigin = '0 0';
    //   document.body.style.width = 'calc(100% / ${scale})';
    // `
    // this.controller.runJavaScript(jsCode)
  }

  build() {
    Column() {
      Row() {
        Text('Web修改字体大小')
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
        Button() {
          Text() {
            SymbolSpan($r('sys.symbol.textformat_size_square'))
              .fontWeight(FontWeight.Medium)
              .fontSize(22)
          }
        }
        .backgroundColor(Color.Transparent)
        .onClick(() => {
          this.isShowPopup = true
        })
      }
      .width('100%')
      .alignItems(VerticalAlign.Center)
      .justifyContent(FlexAlign.SpaceBetween)
      .padding(15)

      Web({ src: 'https://baijiahao.baidu.com/s?id=1851809572329822689', controller: this.controller })
        .layoutWeight(1)
        .textZoomRatio(this.textZoomRatio)
    }
    .bindSheet($$this.isShowPopup, this.fontBuilder, {
      height: 250,
      title: {
        title: '字体大小设置'
      }
    })
  }

  @Builder
  fontBuilder() {
    Column({ space: 30 }) {
      Text('点击下方滑块,可设置Web字体大小')
      SegmentButton({
        options: this.tabOptions,
        selectedIndexes: $tabSelectedIndexes
      })
        .height(44)
    }
    .padding(20)
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
    .width('100%')
  }
}

更多关于HarmonyOS鸿蒙Next中如何修改web资讯页字体大小的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,修改Web资讯页字体大小主要涉及Web组件开发。可通过ArkTS代码设置Web组件的textZoomAtio属性来调整网页文本缩放比例。例如,设置textZoomAtio: 150可将字体放大至150%。此属性作用于WebView内部,影响整个页面的文本渲染。具体实现需在创建Web组件时配置。

在HarmonyOS Next中,修改Web资讯页的字体大小并实现点击设置弹出动态调整功能,核心是通过Web组件的JavaScript注入与ArkTS的交互来完成。以下是关键步骤和代码示例:

  1. Web组件加载与基础配置:使用Web组件加载资讯页,并通过javaScriptAccess启用JavaScript执行权限。

    [@Entry](/user/Entry)
    [@Component](/user/Component)
    struct WebPage {
      controller: WebController = new WebController();
      @State fontSize: number = 16; // 默认字体大小
    
      build() {
        Column() {
          // 设置按钮
          Button('设置字体')
            .onClick(() => {
              // 触发弹出窗逻辑
              this.showFontSizeDialog();
            })
          // Web组件
          Web({ src: 'https://example.com/news', controller: this.controller })
            .javaScriptAccess(true)
            .onPageEnd(() => {
              // 页面加载完成后注入初始字体大小
              this.injectFontSize();
            })
        }
      }
    }
    
  2. 注入CSS调整字体大小:通过runJavaScript方法执行JavaScript代码,动态修改页面CSS。

    // 注入字体样式的方法
    injectFontSize() {
      const jsCode = `
        document.body.style.fontSize = '${this.fontSize}px';
        // 可选:针对特定元素调整
        const articles = document.querySelectorAll('.article');
        articles.forEach(el => el.style.fontSize = '${this.fontSize}px');
      `;
      this.controller.runJavaScript({
        script: jsCode,
        callback: (result) => {
          console.info('字体大小已调整');
        }
      });
    }
    
  3. 实现弹出窗动态调整:使用[@CustomDialog](/user/CustomDialog)创建字体设置弹窗,滑动条实时调整并预览。

    // 自定义弹窗组件
    [@CustomDialog](/user/CustomDialog)
    struct FontSizeDialog {
      @Link fontSize: number;
      private sliderValue: number = 16;
    
      build() {
        Column() {
          Text('调整字体大小')
          Slider({
            min: 12,
            max: 24,
            value: this.sliderValue,
            step: 1
          })
          .onChange((value: number) => {
            this.sliderValue = value;
            this.fontSize = value; // 实时更新State变量
          })
          Button('确定')
            .onClick(() => {
              // 关闭弹窗并应用最终字体大小
              this.fontSize = this.sliderValue;
            })
        }
      }
    }
    
    // 在WebPage中调用弹窗
    showFontSizeDialog() {
      let dialogController: CustomDialogController = new CustomDialogController({
        builder: FontSizeDialog({ fontSize: $fontSize }),
        alignment: DialogAlignment.Bottom
      });
      dialogController.open();
    }
    
  4. 响应式更新:利用ArkTS的响应式能力,监听fontSize变化并自动触发Web页面更新。

    // 监听fontSize变化
    [@Watch](/user/Watch)('fontSize')
    onFontSizeChange() {
      this.injectFontSize(); // 字体大小变更时重新注入
    }
    

注意事项

  • 确保目标Web页面支持CSS字体大小覆盖,部分网站可能通过!important限制样式修改。
  • 若资讯页为单页应用(SPA),需在路由切换后重新注入字体样式。
  • 可通过localStorage持久化用户设置的字体大小,在onPageEnd中读取并应用。

此方案通过ArkTS与Web JavaScript的交互,实现了原生HarmonyOS Next与Web内容的无缝集成,动态调整体验流畅。实际开发中需根据具体页面结构优化CSS选择器。

回到顶部