CSS Variables (custom properties) in Pseudo-element “content” Property

后端 未结 4 1684
太阳男子
太阳男子 2020-12-14 01:44

Example use (what I want)

div::after {
  content: var(--mouse-x) \' / \' var(--mouse-y);
}

Test case showing it NOT working:

CodePe

4条回答
  •  情话喂你
    2020-12-14 02:04

    content property only allows Strings, and since you are dealign with numbers and CSS cannot cast variables, you are left with the option to create another set of variables (from JS) which will serve as the printed values, and will be of type String.

    To set --mouse-x-text as String, it's not enough to cast it to that type using the old casting trick 2+"" = "2", but JSON.stringify is the only way what I know that can output a "real" string, out of the already-string value, which kind-of mean a string of a string, since CSS seems to strip the first string-layer.

    document.addEventListener('mousemove', ({clientX:x, clientY:y}) => {
      const {style} = document.documentElement
    
      style.setProperty('--mouse-x', x)
      style.setProperty('--mouse-y', y)
    
      // for printing
      style.setProperty('--mouse-x-text', JSON.stringify(x+""))
      style.setProperty('--mouse-y-text', JSON.stringify(y+""))
    })
    body::before{
      content: "X:"var(--mouse-x-text)"  Y:"var(--mouse-y-text);
    }

提交回复
热议问题