[英]Background Image not being displayed
我在CDM上设置了背景图片,但是document.body.style={mainBg}
并未按预期设置背景图片,并且它下面的控制台语句打印出一个空字符串。 谁能帮助我找出我做错了什么?
const mainBg = {
backgroundImage: 'url("../img/background.jpg")',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
backgroundAttachment: 'fixed',
backgroundSize: 'cover',
};
class Home extends Component {
componentDidMount() {
console.log(mainBg);
document.body.style = {mainBg};
console.log(document.body.style.backgroundImage)
}
}
编辑 :我正在寻找为身体设置背景图像。
你应该这样尝试
import Background from '../images/background_image.png'; var bckImg = { width: "100%", height: "400px", backgroundImage: `url(${Background})` }; class Section extends Component { render() { return ( <section style={ bckImg }> </section> ); } }
如果<body>
元素位于React.js应用程序之外(通常是这种情况),则可以使用香草javascript,而不是使用React.js设置主体样式。
一种最新的方法(2018年)是使用新的 CSS类型对象模型(CSSOM) ,它将允许您遍历mainBg
并将每个属性和值添加到元素document.body
的attributeStyleMap
属性中document.body
。
工作示例:
const mainBg = { width: '100%', height: '100vh', 'background-image': `url("../img/background.jpg")`, 'background-position': 'center', 'background-repeat': 'no-repeat', 'background-attachment': 'fixed', 'background-size': 'cover', }; for (const declaration in mainBg) { document.body.attributeStyleMap.set(declaration, mainBg[declaration]); console.log('<body> has the declaration: ' + declaration + ': ' + mainBg[declaration] + ';'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.