【问题标题】:Need to set background of a div with a parameter需要用参数设置一个div的背景
【发布时间】:2020-01-04 18:47:35
【问题描述】:

我目前正在尝试根据用户是否选择了背景来设置我的 div 的背景,并且我可以成功地做到这一点。 但是,我不能做的是通过 CSS 设置 div 的背景,因为我不能在 CSS 中连接字符串,这意味着我可以这样做:

background: url("/uploads/Example.png") !important;

但我做不到。

background: url("/uploads/@Model.Banner")

background: url("/uploads/" + @Model.Banner)

我当前的代码如下所示。

<head>
        @if ("/uploads/" + @Model.Banner != "/uploads/")
        {
        <style>
            :root {
                --url: url("/uploads/@Model.Banner");
}
            .profile-header {
            height: 200px;
            background: var(--url) !important;
                background-size: 100%;
                -webkit-border-radius: 10px !important;
                -moz-border-radius: 10px !important;
                border-radius: 10px !important;
            }
        </style>
        }
        </head>

<div id="main">
    <label class="navigation-bar"><a>Home</a> - <a>Users</a> - <b>Profile</b></label>
    <hr />

    <div class="container profile-header"></div>

.profile-header 存在于另一个带有默认横幅的 .css 文件中,这意味着如果存在横幅,代码中的 CSS 将用于动态更改它。

我恳请指导我如何将 div 的背景设置为路径 + 横幅名称,当前代码不起作用,因为它在进入 IF 语句时没有为 div 设置背景。 谢谢!

【问题讨论】:

    标签: html css asp.net asp.net-core-mvc


    【解决方案1】:

    如果您将其添加到相应视图的model,我假设您将知道用户在控制器操作中是否具有Banner 的值。例如:

    public IActionResult Index()
    {
        YourModel model = new YourModel();
    
        ...
    
        // you could supply a default image or just leave as "url(/uploads/)"
        model.BannerUrl = string.IsNullOrEmpty(model.Banner) ? "url(/uploads/Default.png)" : $"url(/uploads/{model.Banner})";
    
        return View(model);
    }
    

    然后在视图中:

    <head>
    @if (!@Model.Banner.Contains("Default.png"))
    {
        <style>
            :root {
                --url: @Model.BannerUrl;
             }
            .profile-header {
            height: 200px;
            background: var(--url) !important;
                background-size: 100%;
                -webkit-border-radius: 10px !important;
                -moz-border-radius: 10px !important;
                border-radius: 10px !important;
            }
        </style>
    }
    </head>
    
    <div id="main">
        <label class="navigation-bar"><a>Home</a> - <a>Users</a> - <b>Profile</b></label>
        <hr />
    
    <div class="profile-header"></div>
    

    或者您可以将其全部添加到内联(只使用了几种样式以便您了解):

    <div style="background:@Model.BannerUrl !important; height: 200px; background-size: 100%"></div>
    

    编辑:

    忘了说可以在下面的视图中工作,但想提供替代选项。

    @{
        var url = $"/uploads/" + @Model.Banner;
    }
    
    <div style="background: url(@url) !important"></div>
    

    【讨论】:

    • 太棒了,这是正确答案。非常感谢!
    猜你喜欢
    • 2017-05-17
    • 2013-07-01
    • 2015-02-21
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    相关资源
    最近更新 更多