From a57acc4f028424090d1e2229325e5d8d5e3ae093 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B4=A4=E5=BF=83?= <3277200+sentsim@users.noreply.github.com> Date: Mon, 28 Aug 2023 11:04:37 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20`lay.getStyleRules()`=20?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E5=8F=8A=E4=BC=98=E5=8C=96=20`lay.style()`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/modules/lay.js | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/src/modules/lay.js b/src/modules/lay.js index 5137763a..550ca47c 100644 --- a/src/modules/lay.js +++ b/src/modules/lay.js @@ -111,32 +111,54 @@ return document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight); }; + // 获取 style rules + lay.getStyleRules = function(style, callback) { + if (!style) return; + + var sheet = style.sheet || style.styleSheet || {}; + var rules = sheet.cssRules || sheet.rules; + + if (typeof callback === 'function') { + layui.each(rules, function(i, item){ + if (callback(item)) return true; + }); + } + + return rules; + }; + // 创建 style 样式 lay.style = function(options){ options = options || {}; var style = lay.elem('style'); var styleText = options.text || ''; - var target = options.target || lay('body')[0]; + var target = options.target; - if(!styleText) return; + if (!styleText) return; // 添加样式 - if('styleSheet' in style){ + if ('styleSheet' in style) { style.setAttribute('type', 'text/css'); style.styleSheet.cssText = styleText; } else { style.innerHTML = styleText; } - lay.style.index = lay.style.index || 0; - lay.style.index++; - - var id = style.id = 'LAY-STYLE-'+ (options.id || 'DF-'+ lay.style.index) - var styleElem = lay(target).find('#'+ id); - - styleElem[0] && styleElem.remove(); - lay(target).append(style); + // ID + style.id = 'LAY-STYLE-'+ (options.id || function(index) { + lay.style.index++; + return 'DF-'+ index; + }(lay.style.index || 0)); + + // 是否向目标容器中追加 style 元素 + if (target) { + var styleElem = lay(target).find('#'+ style.id); + styleElem[0] && styleElem.remove(); + lay(target).append(style); + } + + return style; }; // 元素定位 @@ -467,4 +489,4 @@ }); } -}(window, window.document); // gulp build: lay-footer \ No newline at end of file +}(window, window.document); // gulp build: lay-footer