代码之家  ›  专栏  ›  技术社区  ›  Shtole

未找到CSS变量时记录

  •  0
  • Shtole  · 技术社区  · 5 月前

    当未找到CSS变量时,是否有方法记录浏览器事件?我想知道,因为它似乎对调试有用。假设我有以下代码:

    .stroked-text
    {
        /* Values to define in-place:
    
        --stroked-text-color-1
        --stroked-text-color-2
        --stroked-text-color-3
        --stroked-text-color-bg
    
        */
    
        --gradient: 320deg,
            var(--stroked-text-color-1) 5%,
            var(--stroked-text-color-2) 50%,
            var(--stroked-text-color-3) 90%;
        background: linear-gradient(var(--gradient));
        background-clip: text;
        -webkit-text-stroke: 3px transparent; /* No non-prefixed version. */
        color: black;
    }
    

    我想确定一下 --stroked-text-color-1 在没有视觉检查UI的情况下定义。日志会做这件事。

    当然,我可以使用这样的回退机制:

    var(--stroked-text-color-1, red) /* RED to to attract attention! */
    

    但它也需要目视检查,在某些情况下没有明显错误的值。

    1 回复  |  直到 5 月前
        1
  •  2
  •   ephraimd    5 月前

    真的没有办法在CSS中进行日志记录。但我很确定你可以在这里使用javascript。

    function checkCSSVariableExists(element, variableName) {
        const value = getComputedStyle(element).getPropertyValue(variableName);
        if (!value) {
            console.warn(`CSS Variable "${variableName}" does not exist`);
        }
    }
    
    const element = document.querySelector('.stroked-text');
    checkCSSVariableExists(element, '--stroked-text-color-1');
    

    如果使用JS是你的选择的一部分,这应该是可行的。