虽然这感觉有点像 hack,并且可能无法在所有浏览器中完美运行,但我最近使用的一种方法结合了这样一个事实,即 CSS(至少在 Chrome 中)似乎忽略了属性上设置的无效值,并且我们可以设置自定义属性在无效时回退到默认值。
(注意:我尚未对此进行深入测试,因此将其视为概念/可能想法的 hacky 证明)
以下内容是用 SCSS 编写的,但在标准 CSS 中应该也能正常工作:
.hero-image {
// CSS ignores invalid property values
// When this var is set to an image URL, the browser will ignore it
// When this var isn't set, then we will use the default fallback for the var, which is 'none'
display: var(--loading-page-background-image, none);
// This part isn't directly relevant to my 'if' example, but shows how I was actually using this custom property normally
background-image: var(--loading-page-background-image, none);
}
我正在通过 JavaScript / React 设置自定义属性,但无论您如何设置它都可能会起作用:
// 'true' case
const chosenLoaderUrl = "https://www.example.com/loader.png";
// 'false' case
//const chosenLoaderUrl = "";
// containerRef is just a reference to the div object, you could get this with
// jquery or however you need. Since I'm in React, I used useRef() and attached
// that to my div
containerRef.current.style.setProperty(
"--loading-page-background-image",
`url(${chosenLoaderUrl})`
);
当chosenLoaderUrl 设置为我的网址时,该网址是display 属性的无效值,因此它似乎被忽略了。
当chosenLoaderUrl 设置为空值时,它会回退到我的var() 语句中的默认值,因此将display 设置为none
我不确定这个概念有多“通用”,但我想我会把它添加到这里的其他建议中,以防它对任何人有用。