@aamasri/dom-utils 中文文档教程

发布于 3年前 浏览 27 项目主页 更新于 3年前

Dom Utils

一组 DOM 实用程序,用于添加语法糖和补充 jQuery。

不是 (ES5) 浏览器包。 它是一个 ES6 源模块,旨在“导入”到使用 babel & 转译的 javascript 项目中。 网页包。


Utility Function List


Usage Examples

async ready()

推迟脚本执行,直到 DOM 准备就绪。 实现 Promise 接口。

import { ready } from '@aamasri/dom-utils';

ready().then(function() { 
    alert('Your browser is ready to run scripts...');
});

async loaded()

允许将脚本执行推迟到初始页面呈现之后。 实现 Promise 接口。

import { loaded } from '@aamasri/dom-utils';

loaded().then(function() {
    domUtils.loaded().then(function() { 
        alert('Your browser has finished loading (including images)...');
    });
});

$cache()

重新使用核心 jQuery 对象(可能会节省一些开销)。 提供 $(window)、$(document) 和 $('body') jQuery 对象。

import { $cache } from '@aamasri/dom-utils';

let windowWidth = $cache().$window.width();

isInIframe()

启用检查以防我们的代码在 iframe 中运行。 这样可以避免函数因为在 iframe 中不可用而失败的问题。

import { isInIframe } from '@aamasri/dom-utils';

if (isInIframe) {
    parent.showMessage('I'm executing a parent window function');
} else {
    alert('This is in the iframe');
}

getViewportOffset(element)

返回元素的上、右、下、左偏移量(相对于视口)。

例如,负偏移量意味着该元素被滚动到视图之外。

此函数在相对于指定元素定位另一个元素时也很有用。

import { getViewportOffset } from '@aamasri/dom-utils';

const target = window.getElementById('submitButton');
const targetOffsets = getViewportOffset(target);    // target can be a DOM element or jQuery object

if (targetOffsets.top < 0 || targetOffsets.bottom < 0) {
    target.scrollIntoView();
}

onTopZIndex()

返回页面上最高的 z-index 值。

这对于需要显示在页面上所有其他内容之上的弹出对话框(或通知)很有用。

import { onTopZIndex } from '@aamasri/dom-utils';

$dialog.css({ 'position', 'absolute', 'z-index', onTopZIndex() + 1 });  // position dialog box on top

getZIndex(element, recursive)

获取应用于元素的 z-index 样式。

更有用的是(因为父 z-index 会影响后代),为 effective z-index(即元素的祖先)设置递归选项 true。

import { getZIndex } from '@aamasri/dom-utils';

const dialogLayer = getZIndex(dialog, true);

getAppliedStyle(element, style)

比原生 window.getComputedStyle() 函数更容易使用。

import { getAppliedStyle } from '@aamasri/dom-utils';

const buttonVisible = getAppliedStyle(button, 'display') !== 'none';

webpSupport(feature)

截至 2021 年,浏览器对 webp 图像的完整支持约为 95%。 尽管如此,Safari 直到最近才提供完整的 支持并考虑到许多较旧的 IOS 设备(根本无法升级),此功能可能会有用 到 2024

年。此函数检查特定功能支持(默认情况下为 alpha),因为某些浏览器会逐渐添加功能 首先添加有损图像支持,然后添加无损图像支持。 alpha,最后支持动画图像。

import { webpSupport } from '@aamasri/dom-utils';

// eg. check for full webp support including animation
webpSupport('animation').then(msg => {
    window.browserInfo.webpSupport = true;
    console.log(msg);
}).catch(errorMessage => {
    window.browserInfo.webpSupport = false;
    console.info(errorMessage);
    stripWebp();    // remove unsupported responsive webp images from srcset
});

screenResolution()

系统的一部分,用于确定给定设备的最佳图像分辨率。

根据浏览器视口的大小返回“lo”、“med”或“hi”。

import { screenResolution } from '@aamasri/dom-utils';

const resolution = screenResolution();

wallpaper.src = \`/img/wallpaper-${resolution}.jpg\`;

hash(content)

一个简单、快速(比 md5 等更快)的哈希码生成器。

import { hash } from '@aamasri/dom-utils';

const initialContent = $input.val();
const initialContentSignature = hash(initialContent);

$input.on('change', function() {
    const newContent = $input.val();
    const newContentSignature = hash(newContent);

    if (newContentSignature !== initialContentSignature)
        alert('the input value changed');
});




wallpaper.src = \`/img/wallpaper-${resolution}.jpg\`;



Installation

Dom-utils 是一个 ES6 源模块,旨在导入到您的 ES6 项目中——在使用 Babel/Webpack 转译到浏览器包之前。

$ cd to/your/project
$ npm install @aamasri/dom-utils --save-dev

然后在项目的 ES6 模块中导入并使用它:

Static import

import { ready, loaded, isVisible } from '@aamasri/dom-utils';

ready().then(function() {
    alert('Your browser is ready to run scripts...')
});

Dynamic import

利用 Webpack 的按需(延迟)加载和代码拆分:

import(/* webpackChunkName: "dom-utils" */ '@aamasri/dom-utils').then((domUtils) => {
    domUtils.loaded().then(function() { 
        alert('Your browser has finished loading (including images)...')
    });
});



Package Management

Dom-utils 支持 npm


Dependencies

一些实用函数依赖于 jQuery 包。



Manual release steps

  1. Increment the "version" attribute of `package.json`.
  2. Increment the version number in the `dom-utils.js` file.
  3. Commit
    git commit -a -m "Release version x.x.x - description"
  4. Tag the commit with it's version number
    git tag x.x.x
  5. Change the "latest" tag pointer to the latest commit & push:
    git tag -f latest
    git push origin master :refs/tags/latest
    git push origin master --tags
  6. Publish to npm registry:
    npm publish


Authors

Dom Utils

A collection of DOM utils to add syntactic sugar and supplement jQuery.

This is not an (ES5) browser package. It's an ES6 source module designed to be 'imported' into a javascript project that's transpiled using babel & webpack.


Utility Function List


Usage Examples

async ready()

Defer script execution until the DOM is ready. Implements the Promise interface.

import { ready } from '@aamasri/dom-utils';

ready().then(function() { 
    alert('Your browser is ready to run scripts...');
});

async loaded()

Allows script execution to be deferred until after the initial page render. Implements the Promise interface.

import { loaded } from '@aamasri/dom-utils';

loaded().then(function() {
    domUtils.loaded().then(function() { 
        alert('Your browser has finished loading (including images)...');
    });
});

$cache()

Re-use the core jQuery objects (may save some overhead). Provides the $(window), $(document), and $('body') jQuery objects.

import { $cache } from '@aamasri/dom-utils';

let windowWidth = $cache().$window.width();

isInIframe()

Enables check in case our code is running inside an iframe. This can avoid the problem where a functions fails because it is unavailable inside the iframe.

import { isInIframe } from '@aamasri/dom-utils';

if (isInIframe) {
    parent.showMessage('I'm executing a parent window function');
} else {
    alert('This is in the iframe');
}

getViewportOffset(element)

Returns the top, right, bottom, left offsets of the element (relative to the viewport).

For example, a negative offset means that the element is scrolled out of view.

This function is also useful in positioning another element relative to the specified element.

import { getViewportOffset } from '@aamasri/dom-utils';

const target = window.getElementById('submitButton');
const targetOffsets = getViewportOffset(target);    // target can be a DOM element or jQuery object

if (targetOffsets.top < 0 || targetOffsets.bottom < 0) {
    target.scrollIntoView();
}

onTopZIndex()

Returns the highest z-index value on the page.

This is useful for popup dialog boxes (or notifications) that need to display on-top of everything else already on the page.

import { onTopZIndex } from '@aamasri/dom-utils';

$dialog.css({ 'position', 'absolute', 'z-index', onTopZIndex() + 1 });  // position dialog box on top

getZIndex(element, recursive)

Gets the z-index style applied to an element.

More usefully (because parent z-index affects descendants), set the recursive option true for the effective z-index (ie. the element's ancestry).

import { getZIndex } from '@aamasri/dom-utils';

const dialogLayer = getZIndex(dialog, true);

getAppliedStyle(element, style)

Slightly easier to use than the native window.getComputedStyle() function.

import { getAppliedStyle } from '@aamasri/dom-utils';

const buttonVisible = getAppliedStyle(button, 'display') !== 'none';

webpSupport(feature)

As of 2021 full browser support for webp images is ~95%. Nevertheless, with Safari only recently offering full support and considering many older IOS devices (which simply can't be upgraded), this function will probably be useful through 2024.

This function checks for specific feature support (alpha by default) because some browsers added features incrementally with lossy image support added first, followed by lossless & alpha, and finally support for animated images.

import { webpSupport } from '@aamasri/dom-utils';

// eg. check for full webp support including animation
webpSupport('animation').then(msg => {
    window.browserInfo.webpSupport = true;
    console.log(msg);
}).catch(errorMessage => {
    window.browserInfo.webpSupport = false;
    console.info(errorMessage);
    stripWebp();    // remove unsupported responsive webp images from srcset
});

screenResolution()

Part of a system to determine the optimal image resolution for a given device.

Returns 'lo', 'med' or 'hi' based on the size of the browser viewport.

import { screenResolution } from '@aamasri/dom-utils';

const resolution = screenResolution();

wallpaper.src = \`/img/wallpaper-${resolution}.jpg\`;

hash(content)

A simple, fast (faster than md5 etc) hash code generator.

import { hash } from '@aamasri/dom-utils';

const initialContent = $input.val();
const initialContentSignature = hash(initialContent);

$input.on('change', function() {
    const newContent = $input.val();
    const newContentSignature = hash(newContent);

    if (newContentSignature !== initialContentSignature)
        alert('the input value changed');
});




wallpaper.src = \`/img/wallpaper-${resolution}.jpg\`;



Installation

Dom-utils is an ES6 source module intended to be imported into your ES6 projects - prior to transpiling into a browser bundle with Babel/Webpack.

$ cd to/your/project
$ npm install @aamasri/dom-utils --save-dev

Then import and use it in your project's ES6 modules:

Static import

import { ready, loaded, isVisible } from '@aamasri/dom-utils';

ready().then(function() {
    alert('Your browser is ready to run scripts...')
});

Dynamic import

Leveraging Webpack's on-demand (lazy) loading and code-splitting:

import(/* webpackChunkName: "dom-utils" */ '@aamasri/dom-utils').then((domUtils) => {
    domUtils.loaded().then(function() { 
        alert('Your browser has finished loading (including images)...')
    });
});



Package Management

Dom-utils supports npm under the name @aamasri/dom-utils.


Dependencies

Some of the utility functions depend on the jQuery package.



Manual release steps

  1. Increment the "version" attribute of `package.json`.
  2. Increment the version number in the `dom-utils.js` file.
  3. Commit
    git commit -a -m "Release version x.x.x - description"
  4. Tag the commit with it's version number
    git tag x.x.x
  5. Change the "latest" tag pointer to the latest commit & push:
    git tag -f latest
    git push origin master :refs/tags/latest
    git push origin master --tags
  6. Publish to npm registry:
    npm publish


Authors

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文