我正在使用 ruby on rails 构建一个足球联赛网页。我创建了三个页面(脚手架):新闻、统计和排行榜。它们每个都有一个 scss 文件,并且还受 application.scss
和 scaffolds.scss
的影响。
当我在 stats.scss
中将统计页面的表格(或其他任何东西)的背景颜色更改为红色(只是一种随机颜色)时,新闻和排行榜 View 也会受到影响并将它们的颜色更改为红色,即使我在它们自己的 scss 文件中将它们设置为不同的颜色(如蓝色和绿色)也是如此。
我不明白为什么会这样。 stats.scss
文件不是应该只影响统计 View 吗?
颜色也没有在 application.scss
或 scaffolds.scss
文件中设置,所以我不知道为什么每个 View 都受到 stats.scss
文件。
最佳答案
这是因为 rails(或准确地说是 Assets 管道)将在开发环境的每个页面中包含所有 .scss
文件。右键单击您的 HTML 页面 -> 单击“查看页面源代码”,您可以看到所有 .scss
文件。
Rails 为您提供 css
文件夹中的 news.scss
或 leaderboard.scss
等文件结构,以便您可以组织您的 Controller 特定代码使您的代码生活富有成效。然后,Rails 会将所有这些文件打包并最小化/优化到生产环境中的一个文件 application.scss
中。
When I change the background color of a table (or anything else) for the stats page to red(just a random color) in stats.scss, both the news and leaderboard views are also affected and change their colors to red, even if I had set them to a different color in their own scss files(like blue and green).
这是因为你的 leaderboard
和 news.scss
被先加载,然后 stats.scss
被加载。当您在 application.scss
中使用 require tree .
时,Rails Assets 管道将按升序加载 CSS 文件。因此,leaderboard.scss
和 news.scss
的颜色值不适用,因为最后包含了 stats.scss
。
您应该考虑使用不同的类或制作全局背景类颜色。例如:
// news.scss
.news-table{
background: "yellow";
}
// stats.scss
.stats-table{
background: "red";
}
然后在您的 news.html.erb
文件中,您可以使用:
<table class="news-table">...</table>
或者您可以通过全局方式执行此操作:
// application.scss
.red-bg{
background: red;
}
.yellow-bg{
background: yellow;
}
然后在您的 news.html.erb
和 stats.scss
文件中:
// news.html.erb
<table class="red-bg">...</table>
// stats.html.erb
<table class="yellow-bg">...</table>
关于css - scss 文件影响多个 View 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57493347/