未验证 提交 d7daa46a 编写于 作者: O openharmony_ci 提交者: Gitee

!15222 翻译完成 14100+14264:修改ts-tabs组件通用属性描述

Merge pull request !15222 from ester.zhou/TR-14100
......@@ -123,7 +123,7 @@ export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
// storage is passed to the loadContent API as a parameter.
windowStage.loadContent('pages/index', this.storage)
windowStage.loadContent('pages/Index', this.storage)
}
onWindowStageDestroy() {
......@@ -143,7 +143,7 @@ export default class EntryAbility extends UIAbility {
The **@Component** decorated component obtains data.
```ts
// index.ets
// Index.ets
let storage = LocalStorage.GetShared()
@Entry(storage)
......
......@@ -494,7 +494,7 @@ struct CompA {
this.updateTotal()
}
updateTotal(): number {
updateTotal(): void {
let sum = 0;
this.shopBasket.forEach((i) => {
sum += i
......
......@@ -37,10 +37,10 @@ Creates an **Animator** object.
```js
let options = {
duration: 1500,
easing: 'friction',
easing: "friction",
delay: 0,
fill: 'forwards',
direction: 'normal',
fill: "forwards",
direction: "normal",
iterations: 3,
begin: 200.0,
end: 400.0
......@@ -80,10 +80,10 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro
```js
let options = {
duration: 1500,
easing: 'friction',
easing: "friction",
delay: 0,
fill: 'forwards',
direction: 'normal',
fill: "forwards",
direction: "normal",
iterations: 3,
begin: 200.0,
end: 400.0
......@@ -99,7 +99,7 @@ try {
play(): void
Plays this animation.
Plays this animation. The animation retains the previous playback state. For example, if the animation is set to **reverse** and paused, it will remain in **reverse** when resumed.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
......@@ -247,16 +247,16 @@ Defines animator options.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ---------- | ---------------------------------------- | ---- | ---------------------------------------- |
| duration | number | Yes | Duration for playing the animation, in milliseconds. The default value is **0**. |
| easing | string | Yes | Animation interpolation curve. The default value is **ease**. |
| delay | number | Yes | Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay. |
| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes | State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed.|
| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes | Animation playback mode. The default value is **normal**. |
| iterations | number | Yes | Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times. |
| begin | number | Yes | Start point of the animation interpolation. The default value is 0. |
| end | number | Yes | End point of animation interpolation. The default value is 1. |
| Name | Type | Mandatory| Description |
| ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| duration | number | Yes | Duration for playing the animation, in milliseconds. |
| easing | string | Yes | Animation interpolation curve. Only the following values are supported:<br>**"linear"**: The animation speed keeps unchanged.<br>**"ease"**: The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.<br>**"ease-in"**: The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.<br>**"ease-out"**: The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.<br>**"ease-in-out"**: The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.<br>**"fast-out-slow-in"**: The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0).<br>**"linear-out-slow-in"**: The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0).<br>**"friction"**: The animation uses the damping cubic-bezier curve (0.2, 0.0, 0.2, 1.0).<br>**"extreme-deceleration"**: The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).<br>**"rhythm"**: The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).<br>**"sharp"**: The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).<br>**"smooth"**: The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).<br>**cubic-bezier(x1, y1, x2, y2)**: The animation uses the defined cubic-bezier curve, where the value of the input parameters must range from 0 to 1.<br>**steps(number, step-position)**: The animation uses a step curve. The **number** must be set and only an integer is supported. **step-position** is optional. It can be set to **start** or **end**. The default value is **end**.|
| delay | number | Yes | Animation delay duration, in milliseconds. Value **0** means that there is no delay. |
| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes | State of the animated target after the animation is executed.<br>**"none"**: No style is applied to the target before or after the animation is executed.<br>**"forwards"**: The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed.<br>**"backwards"**: The animation uses the value defined in the first key frame during the **animation-delay**. When **animation-direction** is set to **normal** or **alternate**, the value in the **from** key frame is used. When **animation-direction** is set to **reverse** or **alternate-reverse**, the value in the **to** key frame is used.<br>**"both"**: The animation follows the **forwards** and **backwards** rules.|
| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes | Animation playback mode.<br>**"normal"**: plays the animation in forward loop mode.<br>**"reverse"**: plays the animation in reverse loop mode.<br>**"alternate"**: plays the animation in alternating loop mode. When the animation is played for an odd number of times, the playback is in forward direction. When the animation is played for an even number of times, the playback is in reverse direction.<br>**"alternate-reverse"**: plays the animation in reverse alternating loop mode. When the animation is played for an odd number of times, the playback is in reverse direction. When the animation is played for an even number of times, the playback is in forward direction.|
| iterations | number | Yes | Number of times that the animation is played. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.<br>**NOTE**<br>If this parameter is set to a negative value other than **-1**, the value is invalid. In this case, the animation is played once.|
| begin | number | Yes | Start point of the animation interpolation. |
| end | number | Yes | End point of animation interpolation. |
## Example
......@@ -280,10 +280,10 @@ export default {
onInit() {
let options = {
duration: 1500,
easing: 'friction',
easing: "friction",
delay: 0,
fill: 'forwards',
direction: 'normal',
fill: "forwards",
direction: "normal",
iterations: 2,
begin: 200.0,
end: 400.0
......@@ -293,9 +293,9 @@ export default {
Show() {
let options1 = {
duration: 1500,
easing: 'friction',
easing: "friction",
delay: 0,
fill: 'forwards',
fill: "forwards",
direction: "normal",
iterations: 2,
begin: 0,
......@@ -336,10 +336,10 @@ struct AnimatorTest {
let _this = this
this.backAnimator = animator.create({
duration: 2000,
easing: 'ease',
easing: "ease",
delay: 0,
fill: 'none',
direction: 'normal',
fill: "none",
direction: "normal",
iterations: 1,
begin: 100,
end: 200
......@@ -444,10 +444,10 @@ struct AnimatorTest {
this.flag = false
this.backAnimator.reset({
duration: 5000,
easing: 'ease-in',
easing: "ease-in",
delay: 0,
fill: 'none',
direction: 'normal',
fill: "none",
direction: "normal",
iterations: 4,
begin: 100,
end: 300
......@@ -513,10 +513,10 @@ This API is deprecated since API version 9. You are advised to use [create<sup>9
```js
let options = {
duration: 1500,
easing: 'friction',
easing: "friction",
delay: 0,
fill: 'forwards',
direction: 'normal',
fill: "forwards",
direction: "normal",
iterations: 3,
begin: 200.0,
end: 400.0,
......
......@@ -100,13 +100,13 @@ router.pushUrl({
data3: [123, 456, 789]
}
}
})
.then(() => {
// success
})
.catch(err => {
}, (err) => {
if (err) {
console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
})
return;
}
console.info('pushUrl success');
})
```
## router.pushUrl<sup>9+</sup>
......@@ -473,9 +473,9 @@ Describes the page routing state.
| name | string | No | Name of the current page, that is, the file name. |
| path | string | Yes | Path of the current page. |
## router.enableBackPageAlert<sup>9+</sup>
## router.showAlertBeforeBackPage<sup>9+</sup>
enableBackPageAlert(options: EnableAlertOptions): void
showAlertBeforeBackPage(options: EnableAlertOptions): void
Enables the display of a confirm dialog box before returning to the previous page.
......@@ -499,11 +499,11 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
```js
try {
router.enableBackPageAlert({
router.showAlertBeforeBackPage({
message: 'Message Info'
});
} catch(error) {
console.error(`enableBackPageAlert failed, code is ${error.code}, message is ${error.message}`);
console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`);
}
```
## EnableAlertOptions
......@@ -516,9 +516,9 @@ Describes the confirm dialog box.
| ------- | ------ | ---- | -------- |
| message | string | Yes | Content displayed in the confirm dialog box.|
## router.disableAlertBeforeBackPage
## router.hideAlertBeforeBackPage<sup>9+</sup>
disableAlertBeforeBackPage(): void
hideAlertBeforeBackPage(): void
Disables the display of a confirm dialog box before returning to the previous page.
......@@ -527,7 +527,7 @@ Disables the display of a confirm dialog box before returning to the previous pa
**Example**
```js
router.disableAlertBeforeBackPage();
router.hideAlertBeforeBackPage();
```
## router.getParams
......@@ -574,7 +574,7 @@ Enumerates the routing modes.
| Name | Description |
| -------- | ------------------------------------------------------------ |
| Standard | Standard mode.<br>The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.|
| Standard | Standard mode.<br>The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.<br>**NOTE**<br>If the routing mode is not used, the page is redirected to in standard mode.|
| Single | Singleton mode.<br>If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved as a new page to the top of the stack.<br>If the URL of the target page does not exist in the page stack, the page is redirected to in standard mode.|
## Examples
......@@ -749,7 +749,7 @@ enableAlertBeforeBackPage(options: EnableAlertOptions): void
Enables the display of a confirm dialog box before returning to the previous page.
This API is deprecated since API version 9. You are advised to use [enableBackPageAlert<sup>9+</sup>](#routerenablebackpagealert9) instead.
This API is deprecated since API version 9. You are advised to use [showAlertBeforeBackPage<sup>9+</sup>](#routershowalertbeforebackpage9) instead.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
......@@ -766,3 +766,19 @@ This API is deprecated since API version 9. You are advised to use [enableBackPa
message: 'Message Info'
});
```
## router.disableAlertBeforeBackPage<sup>(deprecated)</sup>
disableAlertBeforeBackPage(): void
Disables the display of a confirm dialog box before returning to the previous page.
This API is deprecated since API version 9. You are advised to use [hideAlertBeforeBackPage<sup>9+</sup>](#routerhidealertbeforebackpage9) instead.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```js
router.disableAlertBeforeBackPage();
```
......@@ -70,39 +70,20 @@ struct ImageAnimatorExample {
ImageAnimator()
.images([
{
src: $r('app.media.img1'),
duration: 500,
width: 170,
height: 120,
top: 0,
left: 0
src: $r('app.media.img1')
},
{
src: $r('app.media.img2'),
duration: 500,
width: 170,
height: 120,
top: 0,
left: 170
src: $r('app.media.img2')
},
{
src: $r('app.media.img3'),
duration: 500,
width: 170,
height: 120,
top: 120,
left: 170
src: $r('app.media.img3')
},
{
src: $r('app.media.img4'),
duration: 500,
width: 170,
height: 120,
top: 120,
left: 0
src: $r('app.media.img4')
}
])
.state(this.state).reverse(this.reverse).fixedSize(false)
.duration(2000)
.state(this.state).reverse(this.reverse)
.fillMode(FillMode.None).iterations(this.iterations).width(340).height(240)
.margin({ top: 100 })
.onStart(() => {
......
......@@ -39,9 +39,10 @@ Rating(options?: { rating: number, indicator?: boolean })
| -------- | -------- |
| onChange(callback:(value: number) =&gt; void) | Triggered when the rating value changes.|
## Example
### Example 1
```ts
// xxx.ets
@Entry
......@@ -95,3 +96,37 @@ struct RatingExample {
```
![rating](figures/rating.gif)
### Example 2
```ts
// xxx.ets
@Entry
@Component
struct RatingExample {
@State rating: number = 3.5
build() {
Column() {
Rating({ rating: this.rating, indicator: false })
.stars(5)
.stepSize(0.5)
.starStyle({
backgroundUri: '/common/imag1.png', // The common folder is at the same level as pages.
foregroundUri: '/common/imag2.png',
secondaryUri: '/common/imag3.png'
})
.margin({ top: 24 })
.onChange((value: number) => {
this.rating = value
})
Text('current score is ' + this.rating)
.fontSize(16)
.fontColor('rgba(24,36,49,0.60)')
.margin({ top: 16 })
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}
```
![rating1](figures/rating1.gif)
......@@ -87,7 +87,7 @@ struct SearchExample {
.searchButton('SEARCH')
.width(400)
.height(40)
.backgroundColor(Color.White)
.backgroundColor('#F5F5F5')
.placeholderColor(Color.Grey)
.placeholderFont({ size: 14, weight: 400 })
.textFont({ size: 14, weight: 400 })
......
......@@ -75,7 +75,7 @@ struct TextTimerExample {
build() {
Column() {
TextTimer({ controller: this.textTimerController, isCountDown: true, count: 30000 })
TextTimer({ isCountDown: true, count: 30000, controller: this.textTimerController })
.format(this.format)
.fontColor(Color.Black)
.fontSize(50)
......
......@@ -70,7 +70,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| onScrollIndex(event: (start: number, end: number) => void) | Triggered when scrolling starts.<br>When calculating the index value, the **\<ListItemGroup>** accounts for one index value as a whole, and the index values of the list items within are not calculated.<br>- **start**: index of the scroll start position.<br>- **end**: index of the scroll end position.|
| onReachStart(event: () => void) | Triggered when the list reaches the start position.|
| onReachEnd(event: () => void) | Triggered when the list reaches the end position.|
| onScrollBegin<sup>9+</sup>(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.<br>- **dx**: amount by which the list will scroll in the horizontal direction.<br>- **dy**: amount by which the list will scroll in the horizontal direction.<br>- **dxRemain**: amount by which the list actually scrolls in the horizontal direction.<br>- **dyRemain**: amount by which the list actually scrolls in the vertical direction.|
| onScrollFrameBegin<sup>9+</sup>(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.<br>\- **offset**: amount to scroll by.<br>\- **state**: current sliding status.<br>- **offsetRemain**: required amount to scroll by in the horizontal direction.|
| onScrollStart<sup>9+</sup>(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\<Scroll>** component or its scrollbar. This event will not be triggered if the scrolling is initiated by using [Scroller](ts-container-scroll.md#scroller).|
| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event will not be triggered if the scrolling is initiated by using [Scroller](ts-container-scroll.md#scroller).|
| onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.<br>- **from**: index of the item before moving.<br>- **to**: index of the item after moving.|
| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: index of the dragged list element.|
......
......@@ -101,8 +101,7 @@ struct ListItemExample2 {
Column() {
List({space:10}) {
ListItem() {
Text(this.message) {
}
Text(this.message)
.width('100%')
.height(100)
.fontSize(16)
......@@ -113,8 +112,7 @@ struct ListItemExample2 {
.swipeAction({ end:this.itemEnd})
ListItem() {
Text(this.message) {
}
Text(this.message)
.width('100%')
.height(100)
.fontSize(16)
......
......@@ -36,20 +36,22 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Horizontal | Only horizontal scrolling is supported. |
| Vertical | Only vertical scrolling is supported. |
| None | Scrolling is disabled. |
| Free<sup>(deprecated) </sup> | Vertical or horizontal scrolling is supported.<br> This API is deprecated since API version 9.|
| Free<sup>(deprecated)</sup> | Vertical or horizontal scrolling is supported.<br>This API is deprecated since API version 9. |
## Events
| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| onScrollBegin<sup>9+</sup>(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Invoked when scrolling starts.<br>Parameters:<br>- **dx**: amount to scroll by in the horizontal direction.<br>- **dy**: amount to scroll by in the vertical direction.<br>Return value:<br>- **dxRemain**: remaining amount to scroll by in the horizontal direction.<br>- **dyRemain**: remaining amount to scroll by in the vertical direction.|
| onScroll(event: (xOffset: number, yOffset: number) => void) | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. |
| onScrollEdge(event: (side: Edge) => void) | Invoked when scrolling reaches the edge. |
| onScrollEnd(event: () => void) | Invoked when scrolling stops. |
| onScrollFrameBegin<sup>9+</sup>(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\<Scroll>** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.<br>\- **offset**: amount to scroll by.<br>\- **state**: current scrolling status.<br>- **offsetRemain**: required amount to scroll by in the horizontal direction.|
| onScroll(event: (xOffset: number, yOffset: number) => void) | Triggered to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. |
| onScrollEdge(event: (side: Edge) => void) | Triggered when scrolling reaches the edge. |
| onScrollEnd(event: () => void) | Triggered when scrolling stops.<br>This event is deprecated since API version 9. Use the **onScrollStop** event instead. |
| onScrollStart<sup>9+</sup>(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\<Scroll>** component or its scrollbar. This event will not be triggered if the scrolling is initiated by using [Scroller](#scroller).|
| onScrollStop<sup>9+</sup>(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event will not be triggered if the scrolling is initiated by using [Scroller](#scroller).|
> **NOTE**
>
> If the **onScrollBegin** event and **scrollBy** API are used to implement nested scrolling, you must set **edgeEffect** of the scrolling child node to **None**. For example, if a **\<List>** is nested in the **\<Scroll>** component, the **edgeEffect** attribute of the **\<List>** must be set to **EdgeEffect.None**.
> If the **onScrollFrameBegin** event and **scrollBy** method are used to implement nested scrolling, set the **edgeEffect** attribute of the scrollable child component to **None**. For example, if a **\<List>** is nested in the **\<Scroll>** component, **edgeEffect** of the **\<List>** must be set to **EdgeEffect.None**.
## Scroller
......@@ -76,7 +78,7 @@ Scrolls to the specified position.
| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| xOffset | Length | Yes | Horizontal scrolling offset. |
| yOffset | Length | Yes | Vertical scrolling offset. |
| animation | {<br>duration: number,<br>curve: [Curve](ts-animatorproperty.md)<br>} | No | Animation configuration, which includes the following:<br>- **duration**: scrolling duration.<br>- **curve**: scrolling curve.|
| animation | {<br>duration: number,<br>curve: [Curve](ts-appendix-enums.md#curve)<br>} | No | Animation configuration, which includes the following:<br>- **duration**: scrolling duration.<br>- **curve**: scrolling curve.|
### scrollEdge
......@@ -104,7 +106,7 @@ Scrolls to the next or previous page.
| Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ------------------------------ |
| next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.|
| direction<sup>(deprecated) </sup> | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.<br> This API is deprecated since API version 9. |
| direction<sup>(deprecated) </sup> | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.<br>This API is deprecated since API version 9. |
### currentOffset
......@@ -131,7 +133,7 @@ Scrolls to the item with the specified index.
> **NOTE**
>
> Only the **\<Grid>**, **\<List>**, and **\<WaterFlow>** components are supported.
> Only the **\<Grid>** and **\<List>** components are supported.
**Parameters**
......@@ -268,13 +270,13 @@ struct NestedScroll {
.onReachEnd(() => {
this.listPosition = 2
})
.onScrollBegin((dx: number, dy: number) => {
if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) {
this.scrollerForScroll.scrollBy(0, -dy)
return { dxRemain: dx, dyRemain: 0 }
.onScrollFrameBegin((offset: number) => {
if ((this.listPosition == 0 && offset <= 0) || (this.listPosition == 2 && offset >= 0)) {
this.scrollerForScroll.scrollBy(0, offset)
return { offsetRemain: 0 }
}
this.listPosition = 1
return { dxRemain: dx, dyRemain: dy };
return { offsetRemain: offset };
})
Text("Scroll Area")
......
......@@ -159,7 +159,7 @@ Grid() {
.fontSize(16)
.textAlign(TextAlign.Center)
.textStyle()
}.rowStart(2).rowEnd(3) // The grid item spans the second and third columns.
}.rowStart(2).rowEnd(3) // The grid item spans the second and third rows.
GridItem() {
Text('4')
......
# Media Query
[Media queries](../reference/apis/js-apis-mediaquery.md) are at the core of responsive design and widely used on mobile devices. You can use them to create different application styles depending on the device type or device state. Specifically, media queries allow you to:
Media queries are widely used on mobile devices. You can use them to modify the application style based on the device type or specific features and device parameters (such as the screen resolution). Specifically, media queries allow you to:
1. Design a layout style based on the device and app attributes.
1. Design a layout style based on the device and application attributes (such as display area, dark light color, and resolution).
2. Update the page layout to adapt to dynamic screen changes (for example, screen splitting or switching between landscape and portrait modes).
## Usage
Invoke the **mediaquery** API to set the media query condition and the callback, and change the page layout or implement service logic in the callback corresponding to the condition.
First, import the mediaquery module, as shown below:
First, import the **mediaquery** module, as shown below:
```ts
import mediaquery from '@ohos.mediaquery'
```
Then, use the **matchMediaSync** API to set the media query condition and save the returned listener, as shown below:
```ts
listener = mediaquery.matchMediaSync('(orientation: landscape)')
```
Finally, register the callback using the saved listener, and change the page layout or implement service logic in the callback. When the media query condition is matched, the callback is triggered. The sample code is as follows:
Finally, register the **onPortrait** callback using the saved listener, and change the page layout or implement service logic in the callback. When the media query condition is matched, the callback is triggered. The sample code is as follows:
```ts
onPortrait(mediaQueryResult) {
if (mediaQueryResult.matches) {
......@@ -33,19 +37,25 @@ onPortrait(mediaQueryResult) {
listener.on('change', onPortrait)
```
## Syntax of Media Query Conditions
## Media Query Conditions
The media query condition consists of the media type (optional), logical operator, and media feature. The logical operator is used to connect different media types and media features. A media feature must be enclosed in parentheses (). There may be multiple media features. The specific rules are as follows:
### Syntax
```
[media-type] [and|not|only] [(media-feature)]
```
Examples are as follows:
`screen and (round-screen: true)` // The query is valid when the device screen is round.
**screen and (round-screen: true)**: The query is valid when the device screen is round.
`(max-height: 800)` // The query is valid when the height does not exceed 800.
**(max-height: 800)**: The query is valid when the height is less than or equal to 800.
`(height <= 800)` // The query is valid when the height does not exceed 800.
**(height <= 800)**: The query is valid when the height is less than or equal to 800.
`screen and (device-type: tv) or (resolution < 2)` // The query is valid only when all media features are true.
**screen and (device-type: tv) or (resolution < 2)**: The query is valid when the device type is TV or the device resolution is less than 2. This is a multi-condition query that contains multiple media features.
### media-type
......@@ -53,59 +63,58 @@ Examples are as follows:
| ------ | -------------- |
| screen | Media query based on screen-related parameters.|
### Media Logic Operation (and|not|only)
### Media Logic Operation (and|or|not|only)
You can use logical operators (**and**, **or**, **not**, and **only**) to compose complex media queries. You can also combine them using comma (,). The following table describes the operators.
**Table 1** Media logical operators
**Table 1** Media logical operators
| Type | Description |
| -------- | ---------------------------------------- |
| and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.<br>For example, **screen and (device-type: wearable) and (max-height: 600) ** indicates that the query is valid when the device type is wearable and the maximum height of the application is 600 pixel units.|
| or | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.<br>For example, **screen and (max-height: 1000) or (round-screen: true)** indicates that the query is valid when the maximum height of the application is 1000 pixel units or the device screen is round. |
| not | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned. In a media query list, logical negation is performed only for the media query using the **not** operator.<br>For example, **not screen and (min-height: 50) and (max-height: 600) ** indicates that the query is valid when the height of the application is less than 50 pixel units or greater than 600 pixel units.<br>**NOTE**<br>When the **not** operator is used, the media type must be specified. |
| only | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:<br>screen and (min-height: 50)<br>The browsers of earlier versions would mislead this sentence into screen, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.<br>**NOTE**<br>When the **only** operator is used, the media type must be specified. |
| ,(comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.<br>For example, **screen and (min-height: 1000), (round-screen: true) ** indicates that the query is valid when the minimum height of the application is 1000 pixel units or the device screen is round.|
| and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.<br>For example, **screen and (device-type: wearable) and (max-height: 600)** indicates that the query is valid when the device type is wearable and the maximum height of the application is 600 pixel units.|
| or | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.<br>For example, **screen and (max-height: 1000) or (round-screen: true)** indicates that the query is valid when the maximum height of the application is 1000 pixel units or the device screen is round.|
| not | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned.<br>For example, **not screen and (min-height: 50) and (max-height: 600)** indicates that the query is valid when the height of the application is less than 50 pixel units or greater than 600 pixel units.<br>You must specify the media type when using the **not** operator.|
| only | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:<br>screen and (min-height: 50)<br>The browsers of earlier versions would mislead this sentence into screen, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.<br>You must specify the media type when using the **only** operator.|
| , (comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.<br>For example, **screen and (min-height: 1000), (round-screen: true)** indicates that the query is valid when the minimum height of the application is 1000 pixel units or the device screen is round.|
At MediaQuery Level 4, range query is imported so that you can use the operators including &lt;=, &gt;=, &lt;, and &gt; besides the max- and min-operators.
**Table 2** Logical operators for range query
**Table 2** Logical operators for range query
| Type | Description |
| ----- | ---------------------------------------- |
| &lt;= | Less than or equal to, for example, **screen and (50 &lt;= height)**.|
| &gt;= | Greater than or equal to, for example, **screen and (600 &gt;= height)**.|
| &lt; | Less than, for example, **screen and (50 &lt; height)**.|
| &gt; | Greater than, for example, **screen and (600 &gt; height)**.|
| &lt; = | Less than or equal to, for example, **screen and (50 &lt;= height)**.|
| &gt; = | Greater than or equal to, for example, **screen and (600 &gt;= height)**.|
| &lt; | Less than, for example, **screen and (50 &lt; height)**.|
| &gt; | Greater than, for example, **screen and (600 &gt; height)**.|
### media-feature
| Type | Description |
| ----------------- | ---------------------------------------- |
| height | Height of the display area on the application page. |
| min-height | Minimum height of the display area on the application page. |
| max-height | Maximum height of the display area on the application page. |
| width | Width of the display area on the app page. |
| min-width | Minimum width of the display area on the application page. |
| max-width | Maximum width of the display area on the application page. |
| Type | Description |
| ----------------- | ------------------------------------------------------------ |
| height | Height of the display area on the application page. |
| min-height | Minimum height of the display area on the application page. |
| max-height | Maximum height of the display area on the application page. |
| width | Width of the display area on the app page. |
| min-width | Minimum width of the display area on the application page. |
| max-width | Maximum width of the display area on the application page. |
| resolution | Resolution of the device. The unit can be dpi, dppx, or dpcm.<br>- **dpi** indicates the number of physical pixels per inch. 1 dpi ≈ 0.39 dpcm.<br>- **dpcm** indicates the number of physical pixels per centimeter. 1 dpcm ≈ 2.54 dpi.<br>- **dppx** indicates the number of physical pixels in each pixel. (This unit is calculated based on this formula: 96 px = 1 inch, which is different from the calculation method of the px unit on the page.) 1 dppx = 96 dpi.|
| min-resolution | Minimum device resolution. |
| max-resolution | Maximum device resolution. |
| min-resolution | Minimum device resolution. |
| max-resolution | Maximum device resolution. |
| orientation | Screen orientation.<br>Options are as follows:<br>- orientation: portrait<br>- orientation: landscape|
| device-height | Height of the device. |
| min-device-height | Minimum height of the device. |
| max-device-height | Maximum height of the device. |
| device-width | Width of the device. |
| min-device-width | Minimum width of the device. |
| max-device-width | Maximum width of the device. |
| device-height | Height of the device. |
| min-device-height | Minimum height of the device. |
| max-device-height | Maximum height of the device. |
| device-width | Width of the device. |
| device-type | Type of the device.<br>Value range: **default** |
| min-device-width | Minimum width of the device. |
| max-device-width | Maximum width of the device. |
| round-screen | Screen type. The value **true** means that the screen is round, and **false** means the opposite. |
| dark-mode | Whether the device is in dark mode. The value **true** means that the device is in dark mode, and **false** means the opposite. |
| dark-mode | Whether the device is in dark mode. The value **true** means that the device is in dark mode, and **false** means the opposite. |
## Example Scenario
Use media queries to apply different content and styles to the page text when the screen is switched between landscape and portrait modes.
In the following example, media queries are used to apply different content and styles to the page text when the screen is switched between landscape and portrait modes.
```ts
import mediaquery from '@ohos.mediaquery'
......@@ -142,8 +151,11 @@ struct MediaQueryExample {
}
}
```
When the device is in landscape orientation, the text content is displayed in landscape mode in the color of #FFD700.<br>
When the device is in landscape orientation, the text content is displayed in landscape mode in the color of #FFD700.
![en-us_image_0000001262954829](figures/en-us_image_0000001262954829.png)
When the device is not in landscape orientation, the text content is displayed in portrait mode in the color of #DB7093.<br>
![en-us_image_0000001263074739](figures/en-us_image_0000001263074739.png)
\ No newline at end of file
When the device is not in landscape orientation, the text content is displayed in portrait mode in the color of #DB7093.
![en-us_image_0000001263074739](figures/en-us_image_0000001263074739.png)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册