Skip to content

这个一个操作 Dom 的工具

Demo

@niu-tools/browser/dom
操作Dom
target node
<template>
    <div>
        <div ref="targetRef">target node</div>
        <a-space>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickHasClass">hasClass</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickAddClass">addClass</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickRemoveClass">removeClass</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickToggleClass">toggleClass</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickSetStyle">setStyle</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickGetStyle">getStyle</a-button>
        </a-space>
        <div style="max-height: 200px;overflow-y: auto;">
            <div v-for="log in logs">{{ log }}</div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { hasClass, addClass, removeClass, toggleClass, setStyle, getStyle } from "@niu-tools/browser/dom";
import { ref } from "vue";

const targetRef = ref<HTMLElement>()

const logs = ref<string[]>([])

function clickHasClass() {
    const result = hasClass(targetRef.value!, "test")
    logs.value.unshift(`hasClass: ${result}`)
}

function clickAddClass() {
    addClass(targetRef.value!, "test")
    logs.value.unshift(`addClass: test`)
}

function clickRemoveClass() {
    removeClass(targetRef.value!, "test")
    logs.value.unshift(`removeClass: test`)
}

function clickToggleClass() {
    toggleClass(targetRef.value!, "test")
    logs.value.unshift(`toggleClass: test`)
}

function clickSetStyle() {
    setStyle(targetRef.value!, {
        color: 'green'
    })
    logs.value.unshift(`setStyle: color green`)
}

function clickGetStyle() {
    const value = getStyle(targetRef.value!, "color")
    logs.value.unshift(`color: ${value}`)
}
</script>
<style scoped>
.test{
    color: red !important;
}
</style>
<template>
    <div>
        <div ref="targetRef">target node</div>
        <a-space>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickHasClass">hasClass</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickAddClass">addClass</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickRemoveClass">removeClass</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickToggleClass">toggleClass</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickSetStyle">setStyle</a-button>
            <a-button style="border: 1px solid black;padding: 0 6px;" @click="clickGetStyle">getStyle</a-button>
        </a-space>
        <div style="max-height: 200px;overflow-y: auto;">
            <div v-for="log in logs">{{ log }}</div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { hasClass, addClass, removeClass, toggleClass, setStyle, getStyle } from "@niu-tools/browser/dom";
import { ref } from "vue";

const targetRef = ref<HTMLElement>()

const logs = ref<string[]>([])

function clickHasClass() {
    const result = hasClass(targetRef.value!, "test")
    logs.value.unshift(`hasClass: ${result}`)
}

function clickAddClass() {
    addClass(targetRef.value!, "test")
    logs.value.unshift(`addClass: test`)
}

function clickRemoveClass() {
    removeClass(targetRef.value!, "test")
    logs.value.unshift(`removeClass: test`)
}

function clickToggleClass() {
    toggleClass(targetRef.value!, "test")
    logs.value.unshift(`toggleClass: test`)
}

function clickSetStyle() {
    setStyle(targetRef.value!, {
        color: 'green'
    })
    logs.value.unshift(`setStyle: color green`)
}

function clickGetStyle() {
    const value = getStyle(targetRef.value!, "color")
    logs.value.unshift(`color: ${value}`)
}
</script>
<style scoped>
.test{
    color: red !important;
}
</style>

setStyle

ts
import { setStyle } from "@niu-tools/browser/dom";

setStyle(targetRef.value!, {
    color: 'green'
})
import { setStyle } from "@niu-tools/browser/dom";

setStyle(targetRef.value!, {
    color: 'green'
})

采用遍历方法一个个设置的值,使用还是简单

hasClass源码
ts
const hasClass = function (obj: HTMLElement, cls: string) {
    const result = obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
    return !!result
}
const hasClass = function (obj: HTMLElement, cls: string) {
    const result = obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
    return !!result
}

getStyle

ts
import { getStyle } from "@niu-tools/browser/dom";

const value = getStyle(targetRef.value!, "color")
import { getStyle } from "@niu-tools/browser/dom";

const value = getStyle(targetRef.value!, "color")

getStyle使用了getComputedStyle,兼容性如下:

https://caniuse.com/?search=getComputedStyle

可以看出还是不错的。 这个函数是返回当前的样式的值,点击查看文档。 根据文档还能获取伪元素的值,因此该函数需要修改

getStyle源码
ts
function getStyle(el: HTMLElement, cssName: keyof CSSStyleDeclaration) {
    const cs = getComputedStyle(el, null)
    return cs.getPropertyValue(cssName as string)
}
function getStyle(el: HTMLElement, cssName: keyof CSSStyleDeclaration) {
    const cs = getComputedStyle(el, null)
    return cs.getPropertyValue(cssName as string)
}

源码

查看源码
dom/index.ts源码
ts
//hasClass===== Start
const hasClass = function (obj: HTMLElement, cls: string) {
    const result = obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
    return !!result
}
//hasClass===== End

//addClass===== Start
const addClass = function (obj: HTMLElement, cls: string) {
    if (!hasClass(obj, cls)) obj.className += ' ' + cls
}
//addClass===== End

//toggleClass===== Start
const removeClass = function (obj: HTMLElement, cls: string) {
    if (hasClass(obj, cls)) {
        const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
        obj.className = obj.className.replace(reg, ' ')
    }
}
//removeClass===== End

//toggleClass===== Start
const toggleClass = function (obj: HTMLElement, cls: string) {
    if (hasClass(obj, cls)) {
        removeClass(obj, cls)
    } else {
        addClass(obj, cls)
    }
}
//toggleClass===== End

//setStyle===== Start
function setStyle(el: HTMLElement, css: Partial<CSSStyleDeclaration>) {
    for (const key in css) {
        if (Object.prototype.hasOwnProperty.call(css, key)) {
            const prop = css[key]
            el.style[key] = prop as string
        }
    }
}
//setStyle===== End

//getStyle===== Start
function getStyle(el: HTMLElement, cssName: keyof CSSStyleDeclaration) {
    const cs = getComputedStyle(el, null)
    return cs.getPropertyValue(cssName as string)
}
//getStyle===== End

export { hasClass, addClass, removeClass, toggleClass, setStyle, getStyle }
//hasClass===== Start
const hasClass = function (obj: HTMLElement, cls: string) {
    const result = obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
    return !!result
}
//hasClass===== End

//addClass===== Start
const addClass = function (obj: HTMLElement, cls: string) {
    if (!hasClass(obj, cls)) obj.className += ' ' + cls
}
//addClass===== End

//toggleClass===== Start
const removeClass = function (obj: HTMLElement, cls: string) {
    if (hasClass(obj, cls)) {
        const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
        obj.className = obj.className.replace(reg, ' ')
    }
}
//removeClass===== End

//toggleClass===== Start
const toggleClass = function (obj: HTMLElement, cls: string) {
    if (hasClass(obj, cls)) {
        removeClass(obj, cls)
    } else {
        addClass(obj, cls)
    }
}
//toggleClass===== End

//setStyle===== Start
function setStyle(el: HTMLElement, css: Partial<CSSStyleDeclaration>) {
    for (const key in css) {
        if (Object.prototype.hasOwnProperty.call(css, key)) {
            const prop = css[key]
            el.style[key] = prop as string
        }
    }
}
//setStyle===== End

//getStyle===== Start
function getStyle(el: HTMLElement, cssName: keyof CSSStyleDeclaration) {
    const cs = getComputedStyle(el, null)
    return cs.getPropertyValue(cssName as string)
}
//getStyle===== End

export { hasClass, addClass, removeClass, toggleClass, setStyle, getStyle }
dom/transform.ts源码
ts
// https://juejin.cn/post/7232209767593656378

// https://juejin.cn/post/7212427549611016253
// function str2dom(str: string) {
//     const parser = new DOMParser();
//     const htmlDoc = parser.parseFromString(str, 'text/html');
//     return htmlDoc.body
// }

// function dom2str(dom: HTMLElement) {
//     return dom.innerHTML
// }
// https://juejin.cn/post/7232209767593656378

// https://juejin.cn/post/7212427549611016253
// function str2dom(str: string) {
//     const parser = new DOMParser();
//     const htmlDoc = parser.parseFromString(str, 'text/html');
//     return htmlDoc.body
// }

// function dom2str(dom: HTMLElement) {
//     return dom.innerHTML
// }

Released under the MIT License.