Lar*_*ard 14 html css asp.net dynamic-data
我有一种情况,我在一个文件夹中有~10-20个不同的背景图像.当我的网站加载时,我需要根据数据库中的某些值选择这些图像中的特定图像.
我想在body标签上使用runat = server,然后在page_load上动态添加属性,但是在我读过这个建议的时候,人们都认为这是一个非常糟糕的主意......而且,我试过了,它没有工作(但没有调试太多).
如何以"正确的方式"做到这一点?:-)
Jon*_*n P 12
您可以通过Generic 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); }
Run Code Online (Sandbox Code Playgroud)
另一种选择是从代码隐藏中获得公开的属性
例如
public string backgroundImage = "defaultImage.png";
Run Code Online (Sandbox Code Playgroud)
在页面init或onload事件中更新此内容.
并在头部的aspx文件中引用它:
<style type="text/css">
body
{
background-image:url(<%=backgroundImage%>);
}
</style>
Run Code Online (Sandbox Code Playgroud)
或者作为body标签的属性
<body style="background-image: url(<%= backgroundImage %>)">
Run Code Online (Sandbox Code Playgroud)
这些都应该能够帮助你.
你可以做到这一点的一种方法是拥有这样的属性(一种方法也可以):
protected string BodyBackgroundImageUrl
{
get
{
// I just chose random pic
return "http://www.google.com/images/logos/ps_logo2.png";
}
}
Run Code Online (Sandbox Code Playgroud)
您不必像这样设置值,您可以稍后从页面Init事件中填充它.
然后在身体中你可以做类似的事情:
<body style='background:url(<%= BodyBackgroundImageUrl %>) no-repeat;'>
Run Code Online (Sandbox Code Playgroud)
不重复只是为了表明你可以写任何你想要的东西.
当然,你甚至可以拥有更多的控制权和不同的方式:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后你的Body标签看起来像:
<body style='<%= GetBodyStyle() %>'>
Run Code Online (Sandbox Code Playgroud)
...
此外,您始终可以使用从页面分配值的隐藏字段,然后在浏览器中通过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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31942 次 |
| 最近记录: |