JavaScript:函数内根据Checkbox状态设置CSS变量命名空间问题
问题解决:根据复选框状态动态生成CSS命名空间
你的问题出在getCode函数的变量作用域上:在if/else块里用const重新声明了nameSpace,这个变量只在块级作用域内有效,外部模板字符串调用的还是全局声明的固定值,导致复选框状态变化无法生效。另外,你初始化的textSizeOutput等变量是页面加载时的静态值,点击按钮时不会同步输入框的最新内容,生成的代码会是旧数据。
修复方案
- 将全局的
nameSpace改为let声明,在if/else逻辑里直接赋值,避免重复声明导致的作用域隔离 - 在
getCode函数内部实时获取输入框的最新值,确保生成的代码是当前配置
修改后的完整代码
// $HELP get code function const preElementRepo = document.getElementById("code"); const copyButton = document.getElementById("copy"); //const textFontOutput = textFontInput.value; const textFontOutput = "'Cormorant Garamond'"; const nameSpacedCheckbox = document.getElementById("namespaced"); let nameSpace = 'typecsset-'; // 改为let,允许后续赋值 copyButton.addEventListener("click", getCode); function getCode(event) { // 根据复选框状态直接更新nameSpace nameSpace = nameSpacedCheckbox.checked ? 'typecsset-' : ''; // 实时获取输入框的最新值 const textSizeOutput = textSizeRemInput.value; const textLeadingOutput = textLeadingInput.value; const textMeasureOutput = textMeasureRemInput.value; preElementRepo.textContent = `:where(html) {\n /* Get your head tag font emebed codes at https://fonts.google.com/specimen/Name+Name */\n --_${nameSpace}text-typeface: var(--${nameSpace}text-typeface, ${textFontOutput});\n --_${nameSpace}text-size: var(--${nameSpace}text-size, ${textSizeOutput}rem);\n --_${nameSpace}text-leading: var(--${nameSpace}text-leading, ${textLeadingOutput});\n --_${nameSpace}text-measure: var(--${nameSpace}text-measure, ${textMeasureOutput}rem); \n\nbody {\n font-family: var(--_${nameSpace}text-typeface);\n font-size: var(--_${nameSpace}text-size);\n line-height: var(--_${nameSpace}text-leading);\n inline-size: var(--_${nameSpace}text-measure);\n}`; alert(`CSS copied to the clipboard. Paste away!`); }
额外提示
后续集成Clipboard API时,可以替换alert提示,用navigator.clipboard.writeText(preElementRepo.textContent)实现更流畅的复制体验。
内容的提问来源于stack exchange,提问作者designtools
相关产品推荐
相关产品推荐

