Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js 与 css 变量 #117

Open
lovelmh13 opened this issue Jul 23, 2021 · 0 comments
Open

js 与 css 变量 #117

lovelmh13 opened this issue Jul 23, 2021 · 0 comments

Comments

@lovelmh13
Copy link
Owner

检测浏览器是否支持 css 变量

const isSupported = window.CSS && window.CSS.supports && window.CSS.supports('--a', 0);
  
if (isSupported) {
    /* supported */
} else {
    /* not supported */
}

使用 js 给 css 动态添加变量

/* ------------ js ------------ */getPropertyValue
document.querySelector('#div').style.setProperty('--data-offset-top', card_offset_scrolltop * -1 + 'px')
/* ------------ css ------------ */
transform: translateY(var(--data-offset-top)) scale(calc(480 / 420))

js 获取 css 中定义的变量

/* ------------ css ------------ */
:root {
  --body-width: 480px;
}
/* ------------ js ------------ */
  
// 方法一:
document.querySelector('#div').getPropertyValue('--body-width')
  
// 方法二:
getComputedStyle(document.documentElement).getPropertyValue('--body-width') // 获取不到上面那种使用 js 动态给 css 添加的变量的值
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant