【HarmonyOS开发】通过媒体查询,实现一次开发,多端部署

 媒体查询(Media Queries)是一种在CSS中使用的技术,用于根据设备的特性和属性(如屏幕宽度、设备类型等)来应用不同的样式规则。通过媒体查询,可以根据不同的设备或屏幕尺寸为用户提供优化的布局和样式。

1、Web中CSS的媒体查询

1.1 根据屏幕宽度应用样式

@media screen and (max-width: 768px) {/* 当屏幕宽度小于等于 768px 时应用的样式 *//* 适用于移动设备或小屏幕 */
}@media screen and (min-width: 769px) and (max-width: 1024px) {/* 当屏幕宽度在 769px 到 1024px 之间时应用的样式 *//* 适用于平板设备或中等屏幕 */
}@media screen and (min-width: 1025px) {/* 当屏幕宽度大于等于 1025px 时应用的样式 *//* 适用于桌面设备或大屏幕 */
}

1.2 根据设备类型应用样式

@media screen and (orientation: landscape) {/* 当设备处于横向(landscape)方向时应用的样式 */
}@media screen and (orientation: portrait) {/* 当设备处于纵向(portrait)方向时应用的样式 */
}@media print {/* 在打印时应用的样式 */
}

1.3 组合多个条件的媒体查询

@media screen and (min-width: 768px) and (max-width: 1024px),(orientation: portrait) {/* 当屏幕宽度在 768px 到 1024px 之间或设备处于纵向方向时应用的样式 */
}

2、Web中JS的媒体查询

可以使用window.matchMedia()方法来执行媒体查询,并根据查询结果执行相应的操作。这个方法返回一个MediaQueryList对象,该对象具有matches属性,表示查询是否匹配。将查询的结果存储在Window全局变量即可。

// 创建一个媒体查询对象
var mediaQuery = window.matchMedia('(max-width: 768px)');// 检查媒体查询的匹配状态
if (mediaQuery.matches) {// 当媒体查询匹配时执行的操作// 适用于移动设备或小屏幕console.log('Media query matches!');
} else {// 当媒体查询不匹配时执行的操作// 适用于平板设备或大屏幕console.log('Media query does not match!');
}// 添加一个媒体查询监听器
mediaQuery.addListener(function(mediaQueryList) {if (mediaQueryList.matches) {// 当媒体查询匹配时执行的操作console.log('Media query matches!');} else {// 当媒体查询不匹配时执行的操作console.log('Media query does not match!');}
});

3、Vue/React中的媒体查询

3.1 Vue中使用媒体查询

3.1.1 计算属性

<template><div :class="containerClass"><p>Content goes here</p></div>
</template><script>
import { ref, onMounted, onUnmounted } from 'vue';export default {setup() {const containerClass = ref('');const updateContainerClass = () => {containerClass.value = window.innerWidth < 768 ? 'small-screen' : 'large-screen';};onMounted(() => {updateContainerClass();window.addEventListener('resize', updateContainerClass);});onUnmounted(() => {window.removeEventListener('resize', updateContainerClass);});return {containerClass};}
};
</script><style>
.small-screen {/* 在小屏幕上应用的样式 */
}.large-screen {/* 在大屏幕上应用的样式 */
}
</style>

3.1.2 三方库(vue-mq)

  • vue-mq(以这个为例)
  • vue-breakpoint-component
  • vue-responsive
  • vue-media-query-mixin
npm install vue-mq
// main.js中配置
import { createApp } from 'vue';
import App from './App.vue';
import VueMq from 'vue-mq';const app = createApp(App);app.use(VueMq, {breakpoints: {mobile: 768,tablet: 1024,desktop: 1280,// 根据需要添加其他断点}
});app.mount('#app');
// 使用
<template><div :class="$mq"><p>Content goes here</p></div>
</template><style>
.mobile {/* 在移动设备上应用的样式 */
}.tablet {/* 在平板设备上应用的样式 */
}.desktop {/* 在桌面设备上应用的样式 */
}
</style>

3.2 React中使用媒体查询(三方库)

  • react-responsive(以这个为主)
  • react-responsive-hooks
  • react-media
  • react-match-media
import React from 'react';
import styles from './MyComponent.module.css';
import { useMediaQuery } from 'react-responsive';const MyComponent = () => {const isSmallScreen = useMediaQuery({ maxWidth: 768 });const isMediumScreen = useMediaQuery({ minWidth: 769, maxWidth: 1024 });const isLargeScreen = useMediaQuery({ minWidth: 1025 });return (<div className={`${styles.container} ${isSmallScreen ? styles.smallScreen : ''} ${isMediumScreen ? styles.mediumScreen : ''} ${isLargeScreen ? styles.largeScreen : ''}`}><p>Content goes here</p></div>);
};export default MyComponent;

4、Harmony中的媒体查询

鸿蒙中主要通过 @ohos.mediaquery 实现媒体查询,进行断点  

// 参考:https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-mediaquery-0000001478181613-V3#ZH-CN_TOPIC_0000001573928789__mediaquerymatchmediasyncimport mediaquery from '@ohos.mediaquery'

4.1 封装媒体查询方法(.ts)

import mediaQuery from '@ohos.mediaquery'class BreakpointSystem {private currentBreakpoint: string = 'md'private smListener: mediaQuery.MediaQueryListenerprivate mdListener: mediaQuery.MediaQueryListenerprivate lgListener: mediaQuery.MediaQueryListenerprivate updateCurrentBreakpoint(breakpoint: string) {if (this.currentBreakpoint !== breakpoint) {this.currentBreakpoint = breakpointAppStorage.Set<string>('currentBreakpoint', this.currentBreakpoint)}console.log('======currentBreakpoint======', this.currentBreakpoint)}private isBreakpointSM = (mediaQueryResult) => {if (mediaQueryResult.matches) {this.updateCurrentBreakpoint('sm')}}private isBreakpointMD = (mediaQueryResult) => {if (mediaQueryResult.matches) {this.updateCurrentBreakpoint('md')}}private isBreakpointLG = (mediaQueryResult) => {if (mediaQueryResult.matches) {this.updateCurrentBreakpoint('lg')}}public register() {this.smListener = mediaQuery.matchMediaSync('(320vp<=width<600vp)')this.smListener.on('change', this.isBreakpointSM)this.mdListener = mediaQuery.matchMediaSync('(600vp<=width<840vp)')this.mdListener.on('change', this.isBreakpointMD)this.lgListener = mediaQuery.matchMediaSync('(840vp<=width)')this.lgListener.on('change', this.isBreakpointLG)}public unregister() {this.smListener.off('change', this.isBreakpointSM)this.mdListener.off('change', this.isBreakpointMD)this.lgListener.off('change', this.isBreakpointLG)}
}export default new BreakpointSystem()

4.2 使用封装的函数

4.2.1 轮播图中使用

import breakpointSystem from '../common/BreakpointSystem'@Component
export default struct IndexSwiper {@StorageProp('currentBreakpoint') currentBreakpoint: string = 'md'@Builder swiperItem(imageSrc) {Image(imageSrc).width('100%').aspectRatio(2.5).objectFit(ImageFit.Fill)}aboutToAppear() {breakpointSystem.register()}aboutToDisappear() {breakpointSystem.unregister()}build() {Swiper() {this.swiperItem($r('app.media.ic_public_swiper1'))this.swiperItem($r('app.media.ic_public_swiper2'))this.swiperItem($r('app.media.ic_public_swiper3'))this.swiperItem($r('app.media.ic_public_swiper1'))this.swiperItem($r('app.media.ic_public_swiper2'))this.swiperItem($r('app.media.ic_public_swiper3'))}.autoPlay(true).indicator(false).itemSpace(10).displayCount(this.currentBreakpoint === 'sm' ? 1 : (this.currentBreakpoint === 'md' ? 2 : 3)).width('100%').padding({ left: 12, right: 12, bottom: 16, top: 16 })}
}

4.2.2 TarBar中使用

import breakpointSystem from '../common/BreakpointSystem'@Entry
@Component
struct Index {@State currentIndex: number = 0@StorageProp('currentBreakpoint') currentBreakpoint: string = 'md'private onTabChange = (index: number) => {this.currentIndex = index}aboutToAppear() {breakpointSystem.register()}aboutToDisappear() {breakpointSystem.unregister()}@BuildertabItem(index: number, title: Resource, icon: Resource, iconSelected: Resource) {TabBarItem({index: index,currentIndex: this.currentIndex,title: title,icon: icon,iconSelected: iconSelected})}build() {Tabs({ barPosition: this.currentBreakpoint === 'lg' ? BarPosition.Start : BarPosition.End }) {TabContent() {Home()}.tabBar(this.tabItem(0, $r('app.string.tabBar1'), $r('app.media.ic_home_normal'), $r('app.media.ic_home_actived')))TabContent() {}.tabBar(this.tabItem(1, $r('app.string.tabBar2'), $r('app.media.ic_app_normal'), $r('app.media.ic_app_actived')))TabContent() {}.tabBar(this.tabItem(2, $r('app.string.tabBar3'), $r('app.media.ic_game_normal'), $r('app.media.ic_mine_actived')))TabContent() {}.tabBar(this.tabItem(3, $r('app.string.tabBar4'), $r('app.media.ic_search_normal'), $r('app.media.ic_search_actived')))}.barWidth(this.currentBreakpoint === 'lg' ? 96 : '100%').barHeight(this.currentBreakpoint === 'lg' ? '60%' : 56).vertical(this.currentBreakpoint === 'lg').onChange(this.onTabChange).backgroundColor('#F1F3F5')}
}

4.3 效果图

5、额外加一个Hilog的封装扩展(.ts)

import hilog from '@ohos.hilog';export class Logger {// 日志对应的领域标识private domain: number = 0xF811;// tag日志标识private prefix: string = '[Logger_Utils]';// 格式字符串,用于日志的格式化输出private format: string = '%{public}s, %{public}s';constructor(prefix: string) {this.prefix = prefix;}debug(...args: string[]): void {hilog.debug(this.domain, this.prefix, this.format, args);}info(...args: string[]): void {hilog.info(this.domain, this.prefix, this.format, args);}warn(...args: string[]): void {hilog.warn(this.domain, this.prefix, this.format, args);}error(...args: string[]): void {hilog.error(this.domain, this.prefix, this.format, args);}
}export default new Logger('[Logger_Utils]');

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/315394.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

centos7通过systemctl启动springboot服务代替java -jar方式启动

背景&#xff1a;以前启动jar包都是通过java -jar&#xff0c;后面了解到一种注册服务式启动jar包的方式&#xff0c;所以做个记录。 注意&#xff1a;我在写该篇博客的时候&#xff0c;给脚本代码都加了#注释来解释该行脚本命令的意思&#xff0c;所以可能出现复制该篇博客脚本…

Linux基础知识点(五-信号)

一、信号的基本概念 1.1 信号的概念 信号&#xff08;signal&#xff09;&#xff0c;又称为软中断信号&#xff0c;用于通知进程发生了异步事件&#xff0c;它是Linux系统响应某些条件而产生的一个事件&#xff0c;它是在软件层次上对中断机制的一种模拟&#xff0c;是一种异…

使用selenium定位csdn主页的收藏夹文章(含完整Python代码)

目录 第一步 导包 代码 第三方库的下载流程 第二步 设置谷歌浏览器及要打开的网页 第三步 定位元素 代码 元素定位方法 前提 准备好流程 第一步 导包 这里需要提前下载好第三方库&#xff1a;selenium&#xff0c;time。代码及selenium第三方库的下载流程如下&#xff…

全面解析Serverless PHP功能、用例和优劣势

无服务器计算是一种基于云的执行模型&#xff0c;可以将应用程序作为服务托管&#xff0c;而无需维护服务器。 服务提供商维护服务器上的资源分配&#xff0c;并根据实际使用情况向用户收费。焦点转移到一个人正在创建的核心应用程序上&#xff0c;基础设施完全由服务提供商处…

python 深度学习 记录遇到的报错问题10

本篇继python 深度学习 解决遇到的报错问题9_module d2l.torch has no attribute train_ch3-CSDN博客 一、CUDA error: no kernel image is available for execution on the device CUDA kernel errors might be asynchronously reported at some other API call,so the stackt…

《2023年企业IoT和OT威胁报告》:物联网恶意软件攻击增长400%

内容概括&#xff1a; 物联网&#xff08;IoT&#xff09;设备无疑改变了我们生活、工作和管理运营技术&#xff08;OT&#xff09;环境的方式。总体而言&#xff0c;到2027年&#xff0c;全球物联网设备数量预计将超过290亿&#xff0c;比2023年的167亿大幅增加。设备和智能技…

C# Winform 在低DPI创建窗体后,在高DPI运行时,窗体会自动拉伸,导致窗体显示不全

C# Winform 在低DPI创建窗体后&#xff0c;在高DPI运行时&#xff0c;窗体会自动拉伸&#xff0c;导致窗体显示不全&#xff0c; 比如在分辨率为100% 的电脑创建C#项目&#xff0c;当运动到分辨率为125%的电脑运行时&#xff0c;后者运行的窗体会自动拉伸&#xff0c;窗体显示…

canvas绘制圆点示例

查看专栏目录 canvas示例教程100专栏&#xff0c;提供canvas的基础知识&#xff0c;高级动画&#xff0c;相关应用扩展等信息。canvas作为html的一部分&#xff0c;是图像图标地图可视化的一个重要的基础&#xff0c;学好了canvas&#xff0c;在其他的一些应用上将会起到非常重…

LabVIEW在高级结构监测中的创新应用

LabVIEW在高级结构监测中的创新应用 LabVIEW作为一个强大的系统设计平台&#xff0c;其在基于BOTDA&#xff08;光时域反射分析&#xff09;技术的结构监测中发挥着核心作用。利用LabVIEW的高效数据处理能力和友好的用户界面&#xff0c;开发了一个先进的监测系统。该系统专门…

json解析本地数据,使用JSONObject和JsonUtility两种方法。

json解析丨网址、数据、其他信息 文章目录 json解析丨网址、数据、其他信息介绍一、文中使用了两种方法作为配置二、第一种准备2.代码块 二、第二种总结 介绍 本文可直接解析本地json信息的功能示例&#xff0c;使用JSONObject和JsonUtility两种方法。 一、文中使用了两种方法…

【计算机毕业设计】SSM实验室设备管理

项目介绍 本项目为后台管理系统&#xff0c;分为管理员、老师、学生三种角色&#xff1b; 管理员角色包含以下功能&#xff1a; 信息管理&#xff1a;用户管理&#xff1b; 基础管理&#xff1a;实验室管理,实验室申请记录,设备管理,设备记录管理,耗材管理,耗材记录管理等功能…

看懂 Git Graph

目录 文章目录 目录Git Graph看懂 GraphVSCode Git Graph 插件1. 选择展示的 Branches2. Checkout 到一个 Branch3. 找到指定 Branch 最新的 Commit4. 找到 Branch 分叉口5. 查看 2 个 Commits 之前的区别 Git Graph Git Graph 是服务于 Git 分支管理的一种可视化工具&#xf…