细米 (fine-mq)
A fine API to manage media queries in JS with ease. It has first-class integration with VueJS.
一个很好的API,可以轻松管理JS中的媒体查询。 它与VueJS具有一流的集成。
安装 (Installation)
Using NPM/Yarn
使用NPM /纱线
npm i fine-mq
# or
yarn add fine-mq
Using unpkg.com
使用unpkg.com
<script src="https://unpkg.com/fine-mq/dist/fine-mq.min.js"></script>
This main file exposes a install
function (Vue plugin), a Mq
class and toMqString
function.
该主文件提供了一个install
函数(Vue插件),一个Mq
类和toMqString
函数。
These are all the builds available via unpkg:
这些是通过unpkg可用的所有构建:
https://unpkg.com/fine-mq/dist/fine-mq.es.js
(es module)https://unpkg.com/fine-mq/dist/mq.cjs.js
(commonjs)https://unpkg.com/fine-mq/dist/mq.es.js
(es module)https://unpkg.com/fine-mq/dist/to-mq-string.cjs.js
(commonjs)https://unpkg.com/fine-mq/dist/to-mq-string.es.js
(es module)
用法 (Usage)
This package is a set of three libs.
该软件包是一组三个库。
A vue plugin that exposes useful properties on vue instances, a component and a directive. This lib includes the two others. (
FineMq
)一个vue插件,它公开了vue实例,组件和指令上的有用属性。 该库包括其他两个库。 (
FineMq
)A media query interface that lets you add/remove aliases to media queries, register/unregister handlers that listen to matching state of a media query or alias. (
Mq
)媒体查询界面,可让您向媒体查询添加/删除别名,注册/取消监听媒体查询或别名的匹配状态的处理程序。 (
Mq
)A lib that exposes a single function that helps you transorm a media query written as a JavaScript object to its string value. (
toMqString
)一个提供单个函数的库,该函数可帮助您将以JavaScript对象形式编写的媒体查询转换为它的字符串值。 (
toMqString
)
Vue插件 (Vue plugin)
Define your breakpoints and/or aliases to media queries and start using them with Vue.
为媒体查询定义您的断点和/或别名,并开始在Vue中使用它们。
import Vue from 'vue'
import FineMq from 'fine-mq'
import App from './App'
// Define your aliases
// NOTE: any size can be expressed as a number, anything that can be casted to a finite number, Infinity, or a size in 'px' or 'em' unit.
Vue.use(FineMq, {
aliases: {
sm: 680, // <=> [0, 680]
md: [681, 1024],
lg: [1025], // <=> [1025, Infinity]
landscape: '(orientation: landscape)',
an_alias_name: {
screen: true,
minWidth: '23em',
maxWidth: '768px'
}
}
})
// or just Vue.use(FineMq). By default aliases are { sm: 680, md: [681, 1024], lg: [1025] }
// => This will register the following aliases:
// {
// sm: '(max-width: 680px)',
// 'sm+': '(min-width: 681px)',
// md: '(min-width: 681px) and (max-width: 1024px)',
// 'md+': '(min-width: 1025px)',
// 'md!': '(min-width: 681px)',
// lg: '(min-width: 1025px)',
// landscape: '(orientation: landscape)',
// an_alias_name: 'screen and (min-width: 380px) and (max-width: 768px)'
// }
// Three reactive properties will then be available on Vue instances:
// - `$mqAliases` is an object that contains the matching state for each alias in the form { [alias]: true/false }.
// - `$lastActiveMQAlias` will contains the last alias that matched and triggered the listener.
// - `$mq` is a Mq instance. See below.
NOTE 1: Absurd modifiers will not be created (ex: when the lower bound is 0, there is no need for the «!» modifier, or if the upper bound is Infinity, there is no need for both «!» and «+» modifiers).
注意1:将不会创建荒谬的修饰符(例如:当下限为0时 ,不需要«!»修饰符,或者如果上限为Infinity ,则不需要«!»和«+ »修饰符)。
NOTE 2: If you specify the unit for your size, the + 1
operation will not be performed.
注意2:如果您为尺寸指定单位,则不会执行+ 1
操作。
Then in your templates, you can use the globally defined MqShow
component or v-mq-show-if
directive.
然后,可以在模板中使用全局定义的MqShow
组件或v-mq-show-if
指令。
The
MqShow
component facilitate conditional rendering with media queries. It renders its content only when one fo the given media queries matches. Cons: If the slot content has multiple root nodes, they will be wrapped by a DIV tag but you can customize the wrapper tag to render with thetag
prop.MqShow
组件有助于通过媒体查询进行条件渲染。 仅当给定的媒体查询之一匹配时,它才会呈现其内容。 缺点: 如果广告位内容具有多个根节点 ,它们将被DIV标签包裹,但您可以自定义包装标签以使用tag
prop进行渲染。
The if
prop if required and can be a String/Array/Object. Modifiers are also supported (for both the component and the directive) by appending it at the end of the alias («+» for greater breakpoints, «!» for current AND greater breakpoints).
如果需要的if
prop可以是String / Array / Object。 通过将修饰符附加在别名的末尾(“ +»表示更大的断点,«!»表示当前的AND更大的断点),还支持修饰符(对于组件和指令)。
<MqShow if="sm">
<!-- slot ...-->
</MqShow>
<!-- or -->
<MqShow if="only screen and (min-width: 200px)"> <!-- any valid media query works -->
<!-- slot ... -->
</MqShow>
<!-- or -->
<MqShow if="md+"> <!-- The `+` modifier here means «above md» -->
<!-- slot ... -->
</MqShow>
<!-- or -->
<MqShow if="md!"> <!-- The `!` modifier here means «md AND above md» -->
<!-- slot ... -->
</MqShow>
<!-- or -->
<MqShow :if="['sm', 'md+']"> <!-- array of aliases (with or without modifier) or valid media queries -->
<!-- slot ... -->
</MqShow>
<!-- or -->
<MqShow :if="{orientation: 'landscape'}"> <!-- object notation is also supported -->
<!-- slot ... -->
</MqShow>
<!-- or -->
<MqShow if="an_alias_name">
<!-- slot ... -->
</MqShow>
The
v-mq-show-if
directive sets the display property of the bound element's style to'none'
only when none of the given media queries matches. Cons: The rendered element will still appear in the DOM tree even if not displayed. Usage is the same as for the component.仅当给定的媒体查询均不匹配时,
v-mq-show-if
指令才将绑定元素的样式的显示属性设置为'none'
。 缺点:即使未显示,渲染的元素仍将出现在DOM树中。 用法与组件相同。
<div v-mq-show-if="'sm'">...</div>
<!-- or -->
<div v-mq-show-if="'only screen and (min-width: 200px)'">...</div>
<!-- or -->
<div v-mq-show-if="'md+'">...</div>
<!-- or -->
<div v-mq-show-if="'md!'">...</div>
<!-- or -->
<div v-mq-show-if="['sm', 'md+']">...</div>
<!-- or -->
<div v-mq-show-if="{orientation: 'landscape'}">...</div>
<!-- or -->
<div v-mq-show-if="'an_alias_name'">...</div>
Mq
API (Mq
API)
The Mq
class exposes a fine API that lets you handle media query changes on your page on the JavaScript side.
Mq
类公开了一个精美的API,可让您在JavaScript端处理页面上的媒体查询更改。
使用范例 (Usage example)
import Mq from 'fine-mq/dist/mq'
const mq = new Mq({
small: 'only screen and (max-width: 480px)',
medium: 'only screen and (min-width: 480px) and (max-width: 720px)'
})
const defaultColor = '#FFF'
const changeColor = color => ({matcher, alias}) => {
document.body.style.backgroundColor = matcher.mathces ? color : defaultColor
}
mq.on('small', changeColor('blue'))
mq.on('medium', changeColor('green'))
mq.on('only screen and (min-width: 720px)', changeColor('red'))
API说明 (API description)
const mq =新的Mq(别名) (const mq = new Mq(aliases))
Initialise a new Mq
. Aliases can be registered afterwards.
初始化新的Mq
。 别名可以随后注册。
mq.alias(alias [,查询])/ mq.unalias(alias) (mq.alias(alias[, query]) / mq.unalias(alias))
Register an alias
for a query
, or register multiple aliases at once via an object.
注册一个alias
为一个query
,或者经由一个对象一次注册多个别名。
mq.alias('small', '(max-width: 100px)')
mq.alias({
small: '(max-width: 100px)',
medium: '(max-width: 200px)'
})
Then you can unregister previously registered aliases with mq.unalias(alias)
.
然后,您可以使用mq.unalias(alias)
取消注册先前注册的别名。
mq.on(查询,回调,上下文) (mq.on(query, callback, context))
Register a callback
which will be executed with the given context
everytime the match state (true/false) for a query or alias. If context
is not specified, it will default to the mq
instance.
注册一个callback
,该callback
将在每次查询或别名的匹配状态(真/假) context
与给定的context
一起执行。 如果未指定context
,它将默认为mq
实例。
// `alias` is the given alias or query and `matcher` is the matchMedia object for that query.
mq.on('(max-width: 400px)', ({matcher, alias}) => {})
mq.on('smartphones', ({matcher, alias}) => {}, {})
mq.off(查询,回调,上下文) (mq.off(query, callback, context))
Remove all callbacks for all queries:
删除所有查询的所有回调:
mq.off()
Remove all callbacks for a query
or alias:
删除query
或别名的所有回调:
mq.off('(max-width: 400px)')
Remove a specific callback
for a query
or alias:
删除query
或别名的特定callback
:
mq.off('(max-width: 400px)', () => {})
Remove a specific callback
with a specific context
for a query
or alias:
删除具有query
或别名的特定context
的特定callback
:
mq.off('(max-width: 400px)', () => {}, {})
Tip: All methods (alias
, unalias
, on
and off
) return this
so that you can chain them.
提示:所有方法( alias
, unalias
, on
和off
)均返回this
以便您可以链接它们。
NOTE: The Mq class is written independantly from toMqString
meaning that the object-style notation for queries is not supported here.
注意: Mq类是独立于toMqString
编写的, toMqString
意味着此处不支持查询的对象样式表示法。
toMqString
(toMqString
)
This function can generate a valid media query string from a javascript object.
此函数可以从javascript对象生成有效的媒体查询字符串。
使用范例 (Usage example)
import toMqString from 'fine-mq/dist/to-mq-string'
toMqString({minWidth: 100, maxWidth: 200});
// -> '(min-width: 100px) and (max-width: 200px)'
媒体类型 (Media type)
toMqString({screen: true}); // -> 'screen'
带否定的媒体类型 (Media type with negation)
toMqString({handheld: false}); // -> 'not handheld'
可以在驼峰情况下指定媒体功能 (Media features can be specified in camel case)
toMqString({minWidth: 100, maxWidth: 200});
// -> '(min-width: 100px) and (max-width: 200px)'
px被添加到数字尺寸值 (px is added to numeric dimension values)
toMqString({minWidth: 100, maxWidth: '20em'});
// -> '(min-width: 100px) and (max-width: 20em)'
可以将多个媒体查询作为数组传递 (Multiple media queries can be passed as an array)
toMqString([{screen: true, minWidth: 100}, {handheld: true, orientation: 'landscape'}]);
// -> 'screen and (min-width: 100px), handheld and (orientation: landscape)'
NOTE: When passing an array to the Vue component/directive and you want it to be considered as one media query like in the last example, remember to wrap it in another array like this: [[{screen: true, minWidth: 100}, {handheld: true, orientation: 'landscape'}]]
(that will register a single listener for 'screen and (min-width: 100px), handheld and (orientation: landscape)' instead of multiple listeners, one for 'screen and (min-width: 100px)' and another for 'handheld and (orientation: landscape)' )
注意:当将数组传递到Vue组件/指令时,您希望像上一个示例一样将其视为一个媒体查询时,请记住将其包装在另一个数组中,如下所示: [[{screen: true, minWidth: 100}, {handheld: true, orientation: 'landscape'}]]
(将为“ screen and(最小宽度:100px),handheld and(orientation:landscape)”注册一个侦听器,而不是为“ screen”注册多个侦听器和(min-width:100px)”,另一个用于“ handheld and(orientation:landscape)”)
翻译自: https://vuejsexamples.com/a-fine-api-to-manage-media-queries-in-js-with-ease/