【问题标题】:Dynamic background-image on body (ASP.NET)身体上的动态背景图像 (ASP.NET)
【发布时间】:2011-07-01 06:19:26
【问题描述】:

我有一个文件夹中有大约 10-20 个不同背景图像的情况。当我的网站加载时,我需要根据数据库中的一些值选择其中一张特定的图片。

我曾考虑在 body 标记上使用 runat=server,然后在 page_load 上动态添加属性,但我在任何地方都读到了人们说这是一个非常糟糕的建议... 另外,我试了一下,还是不行(不过没调试太多)。

如何以“正确的方式”做到这一点? :-)

【问题讨论】:

  • 在 body 中添加一个 style="background-image: url()"(或一个 CSS 类)对我来说是一个很好的解决方案。有什么理由反对它?
  • @Pekka - 出于好奇,这样的事情如何与类而不是内联样式声明一起使用?如果我们选择使用一个类,图像如何是动态的?

标签: asp.net html css dynamic-data


【解决方案1】:

您可以通过通用 HTML 控件动态添加它:

   using System.Web.UI.HtmlControls;


    protected override void OnInit(EventArgs e)
    {
        // Define an Literal control.
        HtmlGenericControl css = new HtmlGenericControl();
        css.TagName = "style";
        css.Attributes.Add("type", "text/css");

        string imageURL = string.Empty;

        //Logic to determin imageURL goes here

        //Update Tag
        css.InnerHtml = @"body{background-image: url(" + imageURL + ");}";


        // Add the Tag to the Head section of the page.
        Page.Header.Controls.Add(css);

        base.OnInit(e);        } 

另一种选择是从代码隐藏中获得公开的属性

例如

public string backgroundImage = "defaultImage.png";

在页面初始化或加载事件中更新此内容。

并在 aspx 文件的头部引用它:

<style type="text/css">
    body 
    { 
       background-image:url(<%=backgroundImage%>);
    }
 </style>

或者作为body标签的一个属性

 <body style="background-image: url(<%= backgroundImage %>)">

其中任何一个都应该能够帮助您。

【讨论】:

    【解决方案2】:

    一种方法是拥有这样的属性(方法也可以):

        protected string BodyBackgroundImageUrl
        {
            get
            {
                // I just chose random pic
                return "http://www.google.com/images/logos/ps_logo2.png";
            }
        }
    

    你不必这样设置值,你可以稍后从页面Init事件中填写。

    然后在正文中,您可以执行以下操作:

        <body style='background:url(<%= BodyBackgroundImageUrl %>) no-repeat;'>
    

    不重复只是为了表明你可以随心所欲地写任何东西。

    当然,您甚至可以拥有更多的控制权和不同的方式:

        public string GetBodyStyle()
        {
            // Get the picture somehow dynamically
            string bodyBackgroundImageUrl = GetBodyBackgroundImageUrl();
    
            // You can use StringBuilder or so, not the main point
            var styles = "";
    
            styles += string.Format("background:url({0}) no-repeat;", bodyBackgroundImageUrl);
    
            // ... Add some extra styles if you want ...
    
            return styles;
        }
    

    然后您的 Body 标签将如下所示:

       <body style='<%= GetBodyStyle() %>'>
    

    ...

    此外,您始终可以使用从页面分配值的隐藏字段,然后在浏览器中通过 JavaScript 将背景 URL 设置为该隐藏字段。

    示例(使用 jQuery,但您不必这样做):

    $(function() {
       // ASP.NET will fill the ID, then # with ID will show to JS as one JS string
       var myHiddenField = $('#<%= myServerSideHiddenField.ClientID %>');
       var bodyBackground = "url(" + myHiddenField.val() + ")";
       document.body.css("background" , bodyBackground);
    });
    

    【讨论】:

      【解决方案3】:

      这就是我们一直以来的做法。

      <body runat="server" id="PageBody">
      

      后面的代码

      PageBody.Style.Add("background-color", "" + returncolor + "");
      

      【讨论】:

        【解决方案4】:

        我正在使用母版页,并从一些建议中获取提示和技巧,我认为这是迄今为止最好、最完整的解决方案:

        请添加这个使用:

        using System.Web.UI.HtmlControls;
        

        母版页内:

        <body runat="server" id="masterPageBody">
        

        在任何代码隐藏页面函数中(例如,“Page_Load”):

        HtmlControl masterPageBody =(HtmlControl)Master.FindControl("masterPageBody");
        masterPageBody.Style.Remove("background-image");
        masterPageBody.Style.Add("background-image", "/images/blah.jpg");
        

        【讨论】:

          【解决方案5】:
                  serverPath = Request.PhysicalApplicationPath;
                  string chosenMap = dropdownlistMap.SelectedItem.Text;
          
                  Bitmap bm = new Bitmap(serverPath + chosenMap);
                  int imageWidth = bm.Width;
                  int imageHeight = bm.Height;
                  bm.Dispose();
          
                  FileInfo fi = new FileInfo(chosenMap);
                  string imageSrc = "~/" + fi.Name;
          
                  imgPanel.BackImageUrl = imageSrc;
                  imgPanel.Width = imageWidth + 4;
                  imgPanel.Height = imageHeight + 4;
                  imgPanel.BorderColor = Color.Yellow;
                  imgPanel.BorderStyle = BorderStyle.Groove;
                  imgPanel.BorderWidth = 2;
          

          【讨论】:

            【解决方案6】:

            说真的——这不必那么难。我刚刚为我正在设计的东西实现了这个......我意识到这个线程可能已经死了,但是嘿——我想出了一个更好的解决方案 IMO。

            ASPX VB:

             ClientScript.RegisterStartupScript(Me.[GetType](), "Background",
            "document.body.style.backgroundImage = " & Chr(34) &
            "url('128-700.jpg')" & Chr(34) & ";", True)
            

            就是这样...我直接从 VB 代码部分调用它。我仍在学习,但我知道在四处搜索和尝试不同的事情之后——这是尽可能直截了当的。

            诀窍在于——这段代码利用了对 Java 的调用来改变背景而不是修改 CSS。

            【讨论】:

              猜你喜欢
              • 2011-08-12
              • 2012-12-16
              • 2012-03-31
              • 1970-01-01
              • 2012-08-02
              • 1970-01-01
              • 2020-10-06
              • 2023-01-28
              • 2013-03-26
              相关资源
              最近更新 更多