0.1.3 • Published 2 months ago

easy-dom-util v0.1.3

Weekly downloads
-
License
-
Repository
github
Last release
2 months ago

easy-dom

Easy-Dom js library for convenient operation of dom


中文 | Version Log | Online Use

TOC

0. Installation and use

0.1 npm installation

npm i easy-dom-util

use

import {dom} from 'easy-dom-util';
let el = dom.div; // Returns an element of type Ele, encapsulating the method of dom operation

0.2 script tag introduction

<script src="https://cdn.jsdelivr.net/npm/easy-dom-util"></script>
<!-- or -->
<!-- <script src="https://cdn.jsdelivr.net/npm/easy-dom-util@x.x.x"></script> -->
<script>
     var el = EasyDom.dom.div;
</script>

1. Ele object

easy-dom encapsulates dom elements. Each dom element will be encapsulated into an Ele element.

Most of the methods on the Ele element support chain calls. The following methods are available for the Ele element:

The method list, detailed usage is below:

MethodParametersReturn valueDescription
dom--HTMLElementReturns the corresponding native dom element
attrjson/name,value/--Ele/string/EleSet or get element attributes
datajson/name/null/--,value/null/--anyTemporarily store and operate some data on dom elements
hasAttrstringbooleanDetermine whether there is a certain attribute
rmAttrstringEle/string/EleDelete attribute
stylejson/name,valueEle/string/EleSet or get element style
textstringstring/EleSet or get element innerText
valuestringstring/EleSet or get element value
htmlstringstring/EleSet or get the element innerHTML
empty--EleClear element content
classstringstring/EleSet the class for the element or get the class name of the element
idstringstring/EleSet id to element or get element's id
clickfunctionEleSet element click event
onjson/name,funcEleSet the event of the element
render{html,method={},result=null}Elerender element
addClassstringEleAdd class to element
rmClassstringEleRemove a class
hasClassstringbooleanDetermine whether there is a certain class
replaceClassstring,stringEleReplace class
append...Arraydom/Ele / Arraydom/EleEleInsert child nodes into elements
insertindex, ...Arraydom/Ele / Arraydom/EleEleInsert child at specified position
prepend...Arraydom/Ele / Arraydom/EleEleHead-insert child
before...Arraydom/Ele / Arraydom/EleEleInsert sibling elements before the element
after...Arraydom/Ele / Arraydom/EleEleInsert sibling elements after the element
removeint/Ele/--Ele/--Remove child nodes based on position or ele element, or delete itself
parentindexEle/nullGet the parent element or nth-level parent element of the element
index--numberGet the position of the element in the parent element
childrenindexEle/ArrayEle/nullGet the first or all child elements
children...Arraydom/Ele / Arraydom/EleEleInsert child nodes into elements
nextindexEle/nullGet the previous or nth element of the element
previndexEle/nullGet the next or nth element after the element
exefunction(dom){}EleExecute a method with Ele as this, and the callback parameter is the corresponding dom element
srcstringEleSet the src attribute of dom
queryselectorArrayEleQuery all children of an element based on css selector

Some API usage examples:

Basic usage

let el = dom.div
     .class('easy-dom')
     .text('easy-dom')
     .click(()=>{
         alert('click')
     })

emmet style

let el = dom('div#app.cls1.cls2[attr1=1][attr2]')

render method

el.render({
     method:{
         alert(text){
             // this : {el,bindEl,self,method}
             console.log(this);
             window.alert(text);
         }
     },
     result(el){
         console.log(el.div1,el.div2);
     },
     // Using the es6-string-html plug-in in vscode will make the following html have syntax highlighting
     html:/*html*/`
         <div @el='div1' @event=alert('test')></div>
         <div @el='div2'></div>
     `
})

.data() Usage

el.data(); // Get data object
el.data(null); // Clear the data object
el.data('name', 'test'); // Set a data
el.data('name'); // Get a data
el.data('name', null); // Remove a data
el.data({ // Batch operation
     name: null, // Remove a data
     age: 12 //Set a data
});

The Ele element has only one attribute, which is .el. Get the corresponding dom element.

2. api list

api list

apiparametersreturn valuedescription
createstringEleGenerate an Ele element based on tag
queryselector,booleanEle/NodeList/nullQuery elements, the following bool parameter indicates whether to query all elements, otherwise only the first one
checkDomstring/selector/HTMLElementHTMLElement/NodeListGet dom elements
classPrefixstring,function--Add a default prefix to the class name. If a callback function is used as a parameter, the prefix will be cleared after the callback is completed. Otherwise, please manually call clearClassPrefix to clear
clearClassPrefix----Clear class name prefix
addCommonStyleobject/name,value--Add css variables and common styles
reportStyle{function, id = 'el-style', usePool = false}--Report css style
initStylePool----Initialize style pool
registTouchEvent{eldom/Ele/selector,touchStart,touchMove,touchEnd}--Mobile touch event encapsulation, compatible with PC
windowSize--{width:height}Get browser size
versionproperties--easy-dom version information

Detailed use

import $, {dom} from 'easy-dom-util';
$.classPrefix('el-test-');
dom.div.class('1') // class = el-test-1
$.clearClassPrefix();
// or
$.classPrefix('el-test-',()=>{
     dom.div.class('1') // class = el-test-1
});

style related

$.addCommonStyle({
     fontSize: '12px',
     textCenter: 'text-align:center;'
})

$.reportStyle({
     func:initStyle,
     id: 'MyStyle' // The id of the style tag
}); // Without using the style pool, the style will be added to the head immediately

// or

$.reportStyle({
     func:initStyle,
     id: 'MyStyle', // id of style tag
     usePool: true
}); // Use the style pool. The style will be added to the head after calling initStylePool. When there are many scattered styles, it is recommended to use the style pool.
$.initStylePool();

function initStyle(common){ // common is the public style
     // Using the es6-string-css plug-in in vscode will make the following css with syntax highlighting
     return /*css*/`
         .el-test-1{
             color:#f44;
             font-size:${common.fontSize};
         }
         .el-test-text{
             ${common.textCenter}
             color:#222;
         }
     `
}

registerTouchEvent

$.registTouchEvent({
     el: 'dom/Ele/selector',
     touchStart(touchList){
     },
     touchMove(touchList){
     },
     touchEnd(touchList){
     },
});

tacl-ui

A set of simple ui components for taost, confirm, loading, alert, drag


Online use

TOC

0. Installation and use

0.1 npm installation

npm i tacl-ui

use

import {tool, toast, confirm, alert, loading, drag} from'tacl-ui';
// or
import TaclUI from'tacl-ui';
// TaclUI = {tool, toast, confirm, alert, loading, drag}

// do something ...

0.2 script tag introduction

<script src="https://cdn.jsdelivr.net/npm/tacl-ui"></script>
<!-- or -->
<!-- <script src="https://cdn.jsdelivr.net/npm/tacl-ui@x.x.x"></script> -->
<script>
    TaclUI.toast('Hello world!')
</script>

1. api

1.1 tool

Expose the easy-dom tool

1.2 toast

Pop up a toast

// simple call
toast(text[, time, position]);
toast('a hint')

// json call
toast({
    text:'A prompt',
    // Other parameters
})

// new method All components in tacl are an instance by default, you can use the new method to create a new instance
const close = toast.new(...);

parameter list

declare interface ToasterOpts {
    text?: string;
    time?: number;
    position?:'top'|'middle'|'bottom';
    parent?: DomEle;
    onhide?(): void;
    onopen?(): void;
    contentHtml?: boolean;
    showClose?: boolean;
    customClass?: string;
    button?: {// add a small button
        text: string;
        onclick(): void;
    }
}

1.2 confirm

A confirm confirmation box pops up

// simple call
confirm('Whether to confirm')
confirm('whether to confirm','confirm box')

// json call
confirm({
    text:'Are you sure?',
    title:'Confirmation box',
    confirmText:'confirm',
    cancelText:'cancel',
    cancelBtn:false, // Do you need a cancel button
    theme:'default', //
}).then((result)=>{
    if (result) {
        
    } else {

    }
})

// new
confirm.new(...).then((result)=>{})

parameter list

declare interface ConfirmerOpts {
    text?:string;
    title?:string;
    confirmText?:string;
    cancelText?:string;
    cancelBtn?:boolean;
    closeBtn?:boolean;
    parent?: DomEle;
    theme?: confirmStyle;
    onhide?(): void;
    onopen?(): void;
    customEl?: DomEle;
    customClass?: string;
    contentHtml?: boolean; // default false
    custom?(box: Ele, $: ToolStatic): void;
    type?: confirmType; // default confirmType.confirm
    onGetCloseMethod?(fn: void): void; // Get the closed function when user new creates a new pop-up box
    clickConfirmClose?: boolean; // default true
    clickCancelClose?: boolean; // default true
    onconfirm?(): void;
    oncancel?(): void;
}

enumerate

declare type confirmResultType ='confirm' |'cancel' |'close';

declare type confirmType ='confirm' |'alert' |'pop';

declare type confirmStyle ='yellow2' |'yellow' |'default';

1.3 alert

Pop up an alert

// simple call
alert('success')
alert('success','success title')

// json call
alert({
    text:'Success',
    title:'Success Title',
    confirmText:'confirm',
    theme:'default', //
}).then(()=>{

})

// new
alert.new(...).then((result)=>{})

parameter list

Same as confirm

1.4 pop

Pop up a pop-up box

// simple call
pop('Are you sure?')
pop('Are you sure?','Confirmation box')

// json call
pop({
    text:'Are you sure?',
    title:'Confirmation box',
    confirmText:'confirm',
    cancelText:'cancel',
    cancelBtn:false, // Do you need a cancel button
    theme:'default', //
}).then((result)=>{
    if (result) {
        
    } else {

    }
})

// new
pop.new(...).then((result)=>{})

parameter list

Same as confirm

1.5 loading

Pop up a loading

// simple call
loading(text[,time]);
loading();
loading('Loading...');
loading('Loading...', 1000);

loading.close(); // Manually close

// json call
loading({
    text:'Success',
    time:1000
})

const close = loading.new(...);

parameter list

declare interface LoadingerOpts {
    text?:string;
    time?:number|null;
    parent?: DomEle;
    backgroundOpacity?: number;
    onopen?(): void;
    onhide?(): void;
}

1.6 drag

Generate a draggable element, compatible with pc and mobile

let el = drag({
    el,
    parent,
    enableDrag = true,
    onClick = df,
    onSideChange = df,
    zIndex = 100,
    aside = false,
    preventDefault = true,
    reinitPosition = false,
    margin = 3, // upper right lower left or just pass in a number
})

parameter list

ParameterMustTypeDefault ValueDescription
elYesdom/Ele/selector-Elements to be dragged
parentNodom/Ele/selector-Specify a parent element, so that the drag can only be carried out in the parent element, and the parent element needs to set the position style
enableDragNobooleantrueWhether it can be dragged or not
onClickNofunctionfunction(){}Click event
asidenobooleanfalsewhether to be adsorbed on both sides
onSideChangeNofunctionfunction(isLeft){}Only takes effect when aside=true, and triggers when the suction side changes
zIndexNonumber100z-index of the dragged element
preventDefaultNobooleantrueWhether to prohibit the default event behavior
marginNonumber/Arraytop,right/bottom/left3Top, bottom, left, and right margins
reinitPositionNobooleanfalseWhether to change the position of the drag according to the orientationchange and resize events, it needs to be turned on when the drag is full screen
declare interface DragParameters {
    el: Ele|HTMLElement|string;
    parent?: Ele|HTMLElement|string;
    onClick?: (event: Event, endX: number, endY: number) => {};
    onSideChange?: (isLeft:boolean) => {};
    zIndex?: number;
    enableDrag?:boolean;
    delay?:number;
    aside?:boolean;
    preventDefault?:boolean;
    reinitPosition?:boolean;
    margin?:number|Array<number>;
    onDragStart?: (event: Event, x: number, y: number) => {};
    onDragMove?: (event: Event, x: number, y: number) => {};
    onDragEnd?: (event: Event, x: number, y: number) => {};
}

declare class Drag {
    constructor(parameters: DragParameters);
    setPosition(left: number, top: number): void;
    initPosition(): void;
    getParentSize(): {width: number, height: number};
    aside: boolean;
    sideLeft: boolean;
    enableDrag: boolean;
    preventDefault: boolean;
    left: number|string;
    top: number|string;
    margin: Array<number>;
}

Remarks: Regarding preventDefault, preventDefault=true can prohibit the dragging of the browser on the mobile terminal to cause the page to move, and there is a blank at the top But this attribute will also prohibit the click event of the child element, which can be circumvented by the target attribute of the event in the onClick event Both methods have their pros and cons

Attribute list

preventDefault, enableDrag, aside

The use is the same as the parameter list, and the properties can be dynamically modified after generation

0.1.3

2 months ago

0.1.0

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago

0.0.28

2 years ago

0.0.29

2 years ago

0.0.27

4 years ago

0.0.26

4 years ago

0.0.25

4 years ago

0.0.24

4 years ago

0.0.23

4 years ago

0.0.22

4 years ago

0.0.21

4 years ago

0.0.20

4 years ago

0.0.18

4 years ago

0.0.19

4 years ago

0.0.17

4 years ago

0.0.16

4 years ago

0.0.15

4 years ago

0.0.14

4 years ago