本文介绍了asp.net C#如何以编程方式在Page_Load中变身背景图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这里做简单的网页是我的身体在HTML code

I'm trying to make simple webpage here is my body in HTML code

  <body runat="server" id="BodyTag" style="height: 1171px; width: 1148px;">
        <form id="form1" runat="server">

在Page_Load中在我的Form.aspx.cs文件我想要生成1到x随机数
其中X是文件的数量在一个特定的文件夹(包含图片的文件夹),那么我想身体的背景图像是这个随机生成的数字,只要文件夹中的图片名称是1,2,...,...这里是我的code

On Page_Load in my Form.aspx.cs file i want to generate random number from 1 to Xwhere X is the number of files in a specific folder(folder containing images) then i want the body background image to be this random generated number as long as the image names in the folder are 1,2, ... , ... Here is my code

protected void Page_Load(object sender, EventArgs e)
        {
            string path = "C:/Users/FluksikartoN/documents/visual studio 2012/Projects/FLUKSIKARTON/FLUKSIKARTON/WebPhotos/BackGroundPhotos";
            int countF = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;
           Random rand = new Random((int)DateTime.Now.Ticks);
            int n = rand.Next(1, countF);
            BodyTag.Style["background-image"] = "C:/Users/FluksikartoN/documents/visual studio 2012/Projects/FLUKSIKARTON/FLUKSIKARTON/WebPhotos/BackGroundPhotos/" + n.ToString() + ".jpg";



        }

体的背景图像不改变,它保持白色,我不明白why.Please不要犹豫,问的详细信息,如果您需要

body background image does not change, it stays white and i dont understand why.Please do not hesitate to ask more information if you need

推荐答案

这是更好地与CSS来实现的。既然你需要一种方法来从code去做,这就是我脑海中最简单的选择是生成的JavaScript做

This is better achieved with css. Since you need a way to do it from code, the easiest option that comes to my mind is do it with generated Javascript

的JavaScript

 <script type="text/javascript">
     document.body.style.background = "url('http://localhost:53942/images/_65209699_fanbase_bbc.jpg')";
     document.body.style.backgroundRepeat = 'no-repeat';
 </script>

将其应用到您的code

protected void Page_Load(object sender, EventArgs e)
{
    string script = "<script type=\"text/javascript\">
             document.body.style.background = \"url('http://localhost:53942/images/_65209699_fanbase_bbc.jpg')";
             document.body.style.backgroundRepeat = 'no-repeat';
         </script>\";

    ClientScript.RegisterClientScriptBlock(this.GetType(), "background-changer-script", script);
}

这只会波及的JavaScript到您的网页的底部,会被浏览器执行,改变背景预期。检查可以设置其他背景属性为Javascript智能感知和CSS

This will just spill the Javascript to the bottom of your page and will be executed by the browser, changing the background as expected. Check the intellisense for Javascript and CSS for other background properties that can be set

这篇关于asp.net C#如何以编程方式在Page_Load中变身背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 20:26