javascript - .NET MVC Razor - 作用域样式

标签 javascript html css asp.net-mvc-4 razor

目前,我正在尝试在我的其中一个 View 中使用局部 View ,该 View 使用不同 css 样式表。但是,由于在 Razor 中呈现样式的方式,主视图中的样式被继承: ' 似乎在 Razor 中找到任何关于 scoped css 的文档。

执行下面的代码是行不通的 - 我相信是因为 Razor 处理 Styles.Render 只是简单地放在头部。

<div>
    <style scoped>
        @Styles.Render("~/Content/othercss")
    </style>
    @Html.Partial("~\\Views\\Layouts\\blog.cshtml")
</div>

有人知道解决这个问题的方法吗?

最佳答案

Styles.Render() 为浏览器呈现链接标签以抓取 CSS 文件,如下所示:

<link rel="stylesheet" type="text/css" href="https://whatever.css">

这不是 style 元素中预期的内容。你想要做什么它输出那个 CSS 文件的内容,例如:

<style scoped>
    @Html.Raw(File.ReadAllText(Server.MapPath("~/Content/yourfile.css")))
</style>

请注意,这不是在使用您的包,要做到这一点,您需要访问包并以某种方式呈现它(超出此答案的范围)。

说了这么多,请注意 docs对于 scoped 属性,这样说:

Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behaviour my change in the future.

Obsolete This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

更好的选择是首先确定 CSS 的范围。例如:

div#wrapper .red {
    background-color: red;
}

现在这种样式只适用于 ID 为 wrapperdiv。答:如果您使用 SASS 之类的工具编写 CSS(您真的应该这样做!),则更容易:

div#wrapper {

    .red {
        background-color: red;
    }
    .some-other-style {
        display: block
    }
}

关于javascript - .NET MVC Razor - 作用域样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306558/

相关文章:

css - 颜色标签不适用于 QPushButtons

javascript - 在动态创建的元素上实现 jQuery

html - 相对调整子div的位置

JavaScript onClick 按钮将文本区域添加到特定的 div 元素中

css - 将 -webkit-tap-highlight-color 应用于空白会导致 phonegap 应用程序出现故障

html - 响应式设计 - 图像不按比例缩放

javascript - 我的图像在我的文字之后呈现,我该如何解决这个问题

javascript - 为什么从 JSON 文字到类型的转换不包括函数

javascript - qTip(jQuery 插件)如何删除页面中的所有 q 提示?

javascript - 获取 html5 select 中所选选项的键(文本)