From 2b5eb355bce983fc44c2e686dc255f2b5b63a5ff Mon Sep 17 00:00:00 2001 From: xuliangzhan Date: Mon, 26 Aug 2024 21:41:41 +0800 Subject: [PATCH] Support css variables #2 --- README.md | 16 ++++++++++++++++ index.ts | 30 ++++++++++++++++++++++++++++++ package.json | 2 +- 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index db03685..2fd6d74 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,22 @@ let currZIndex2 = 2000 currZIndex2 = domZIndex.getCurrent(currZIndex2) // 1500 ``` +## Css var + +Using css variables. + +* ```--dom-main-z-index``` be equivalent to ```getCurrent()``` +* ```--dom-sub-z-index``` be equivalent to ```getSubCurrent()``` + +```css +.my-popup { + z-index: var(--dom-main-z-index); +} +.my-msg { + z-index: var(--dom-sub-z-index); +} +``` + ## Contributors Thank you to everyone who contributed to this project. diff --git a/index.ts b/index.ts index 2e4511b..d7b33a9 100644 --- a/index.ts +++ b/index.ts @@ -1,5 +1,9 @@ let storeEl: HTMLElement | null = null let storeId = 'z-index-manage' + +let styleEl: HTMLStyleElement | null = null +let styleId = 'z-index-style' + let storeMainKey: 'm' = 'm' let storeSubKey: 's' = 's' @@ -29,6 +33,29 @@ function getDomMaxZIndex () { return max } +function getStyle () { + if (!styleEl) { + if (isDocument()) { + styleEl = document.getElementById(styleId) as HTMLStyleElement + if (!styleEl) { + styleEl = document.createElement('style') + styleEl.id = styleId + document.getElementsByTagName('head')[0].appendChild(styleEl) + } + } + } + return styleEl +} + +function updateVar () { + let styEl = getStyle() + if (styEl) { + let prefixes = '--dom-' + let propKey = '-z-index' + styEl.innerHTML = ':root{' + prefixes + 'main' + propKey + ':' + getCurrent() + ';' + prefixes + 'sub' + propKey + ':' + getSubCurrent() + '}' + } +} + function getDom () { if (!storeEl) { if (isDocument()) { @@ -60,6 +87,7 @@ function createSetHandle (key: keyof (typeof storeData)) { } } } + updateVar() return storeData[key] } } @@ -121,4 +149,6 @@ const DomZIndex = { getMax: getDomMaxZIndex } +updateVar() + export default DomZIndex diff --git a/package.json b/package.json index 1369d46..fad2876 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dom-zindex", - "version": "1.0.4", + "version": "1.0.5", "description": "Web common z-index style management", "files": [ "dist",