gpt4 book ai didi

CSS 为子元素提供与祖 parent 相同的背景。祖 parent 的背景由Javascript设置

转载 作者:行者123 更新时间:2023-12-02 21:05:24 25 4
gpt4 key购买 nike

这可能只能在 JS 中实现。我正在为页面进行响应式设计。仅当最大宽度为 768px 时,我才需要一个子元素与其父元素具有相同的背景图像。需要注意的是,父级的背景图像是由 JavaScript 根据用户点击的内容设置的。

@media all and (max-width: 768px) {
// background-image: inherit from grandparent?
}

最佳答案

要从父元素继承属性值,可以使用 inherit关键字:

If the cascaded value of a property is the inherit keyword, the inherited value becomes the property’s specified and computed values.

background-image: inherit;

var el = document.querySelector('#target'),
bg = 'linear-gradient(to right, #ff0 33%, #0ff 33%, #0ff 66%, #f0f 66%)';
el.style.backgroundImage = bg;
div {
padding: 20px 20%;
}
@media all and (max-width: 768px) {
p {
border: 5px solid black;
background-image: inherit;
}
}
<div id="target"><p>Hello</p></div>

如果您想从祖先继承多个级别,您可以对所有级别使用inherit,但结果可能并不理想:

var el = document.querySelector('#target'),
bg = 'linear-gradient(to right, #ff0 33%, #0ff 33%, #0ff 66%, #f0f 66%)';
el.style.backgroundImage = bg;
div {
padding: 20px 20%;
background-image: inherit;
}
@media all and (max-width: 768px) {
p {
border: 5px solid black;
background-image: inherit;
}
}
<div id="target"><div><div><p>Hello</p></div></div></div>

或者,如果browser support不是问题,你可以使用 CSS 变量:

el.style.setProperty('--bg', bg);
background-image: var(--bg);

var el = document.querySelector('#target'),
bg = 'linear-gradient(to right, #ff0 33%, #0ff 33%, #0ff 66%, #f0f 66%)';
el.style.setProperty('--bg', bg);
div {
padding: 20px 20%;
}
#target {
background-image: var(--bg);
}
@media all and (max-width: 768px) {
p {
border: 5px solid black;
background-image: var(--bg);
}
}
<div id="target"><div><div><p>Hello</p></div></div></div>

关于CSS 为子元素提供与祖 parent 相同的背景。祖 parent 的背景由Javascript设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36320556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com