I'm trying to change background image by accessing DOM and changing css property like so:
///anotherweathermap.js
const changePic = () => {
document.getElementById('bckgAnother').style.backgroundImage = "url(../img/kaunas.jpg)";
}
The image will not load but when I put the img path in css, the img path is different:
If I insert the same path, the one with static/media.., the DOM manipulation works. This is the order of files:
Relative URLs in CSS images are computed between the location of the style sheet (which will be the URL of the webpage itself for inline CSS) and the URL of the image.
They have nothing to do with either:
Since you are using React, you will need to import
the image and then use the imported value of it to get the URL.
You should change your logic to set the value based on state and avoid direct DOM manipulation.
import Default from '../img/default.jpg';
import Kaunas from '../img/kaunas.jpg';
const AnotherWeatherMap = (props) => {
const [background, setBackground] = useState(Default);
const css = {
backgroundImage: `url(${background})`
};
return (<div style={css}>
<button onClick={ () => setBackground(Kaunas) }>Change background<button>
</div>);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.