某些样式未与webpack一起应用

bbuxkriu  于 5个月前  发布在  Webpack
关注(0)|答案(3)|浏览(59)

我正在学习将模块与webpack捆绑在一起,遇到了一个问题。在我的src文件夹中,我创建了一个CSS文件(style.css),一个JS文件(home.js),其中包含一个函数和一个JS文件(index.js),我在添加到页面之前将它们导入其中。
我在style.css的主体中添加了一个背景图片,加载正常,但是我应用于一个元素('hi' div)的样式似乎没有应用。当检查页面上的元素时,elements类确实显示出来。
为什么这不起作用-我没看到什么?
所有三个文件都粘贴在这里:

//index.js:

console.log('hello world');
import square from './home.js';
import './style.css';
const content = document.getElementById('content');

content.appendChild(square());

//home.js:

export default function square() {
    const hi = document.createElement('div');
    hi.classList.add('black');
    hi.textContent = 'boo';

    return hi
};

//style.css:

body {
    margin: 0;
    padding: 0;
    height: 100vh;
    width: 100wv;
    background-image: url('food.jpg');
    background-size: cover;
};

.black {
    background-color: black;
    color: white;
    border: 1px solid;
    padding: 10px;
  }

字符串

2admgd59

2admgd591#

这是因为你的组件比你的style.css先加载。

euoag5mw

euoag5mw2#

你可以看到下面的文章希望这解决问题

const style = document.createElement('style');
    style.innerHTML = `
          .note {
            color:"#000";
          }
        `;

document.head.appendChild(style);

字符串
下面链接有几个示例
https://www.javascripttutorial.netenter code here/dom/css/add-styles-to-an-element/#:~:text= First%2C%20select%20the%20element%20by,properties%20of%20the%20style%20对象。

k5ifujac

k5ifujac3#

//我更希望你使用这个,你也可以在旅途中提供动态css

var temp = document.getElementById("temp");

const dynamicValue = 10; 
const darkMode = true;

const styles = `
    background-color:${darkMode ? '#000' : '#fff'};
    color:${darkMode ? '#fff' : '#000'};
    width:${innerWidth - 100}px;
    height:${innerHeight - 100}px;
    display:inline-block;
    border-radius:${dynamicValue}px;
`

temp.setAttribute("style", styles)

字符串

相关问题