¿Es posible actualizar una hoja CSS con una devolución de datos AJAX?
-
21-08-2019 - |
Pregunta
He estado aprendiendo a crear imágenes dinámicas y hojas de estilo dinámicas usando ASP.NET 3.5.Mi razonamiento detrás de esto es que tengo una página web en la que quiero cambiar la imagen de fondo del encabezado (configurada con CSS) automáticamente.Consulte a continuación mi script de prueba:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<%
Response.Output.WriteLine("<link rel=""Stylesheet"" type=""text/css"" href=""style.aspx?t={0}&v={1}"" />", oType, oText)
%>
</head>
<body>
<form id="form1" runat="server" action="Default.aspx">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="testheader"> </div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <%-- for testing --%>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>
Entonces, no hay nada especial en la página de formulario predeterminada anterior, tiene un estilo DIV para tener la imagen de fondo dinámica y una etiqueta, que como indica el comentario es solo para asegurarse de que mi AsyncPostBack esté funcionando correctamente.
Partial Class _Default
Inherits System.Web.UI.Page
Public oType As String = "m"
Public oText As String = "Genius on the Web"
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Select Case oType
Case "m"
oType = "c"
Case "c"
oType = "m"
End Select
Label1.Text = Now.ToString
End Sub
End Class
De nuevo, nada especial.Simplemente intercambia los dos valores que he codificado temporalmente en el programa y actualiza el texto de la etiqueta.
Esta es mi hoja de estilo dinámica:
<%@ Page Language="VB" %>
<%
Response.ContentType = "text/css"
Dim qString As String = Request.QueryString("t")
Dim bText As String = Request.QueryString("v")
If String.IsNullOrEmpty(qString) Then qString = "blank"
If String.IsNullOrEmpty(bText) Then bText = "Placeholder"
Dim theColor, H1size, bannerImg As String
Select Case qString
Case "c"
theColor = "green"
H1size = 30
Case "m"
theColor = "blue"
H1size = 26
Case Else
theColor = "red"
End Select
bannerImg = String.Format("image.aspx?t={0}&p={1}", Server.UrlEncode(bText), qString)
%>
body { background-color: <%=theColor%>; }
.testheader { background: url(<%=bannerImg%>); background-repeat:no-repeat; height:120px; }
.testclass { font-size: <%=H1size%>px; border:1px solid yellow; margin-bottom:2em; }
Finalmente, aquí está mi script de imagen dinámica:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.ContentType = "image/jpeg"
Response.Clear()
Response.BufferOutput = True
Try
Dim oText As String = Server.HtmlDecode(Request.QueryString("t"))
If String.IsNullOrEmpty(oText) Then oText = "Placeholder"
Dim oPType As String = Server.HtmlDecode(Request.QueryString("p"))
If String.IsNullOrEmpty(oPType) Then oPType = "none"
Dim imgPath As String = ""
Select Case oPType
Case "c"
imgPath = "img/banner_green.jpg"
Case "m"
imgPath = "img/banner_blue.jpg"
Case Else
Throw New Exception("no ptype")
End Select
Dim oBitmap As Bitmap = New Bitmap(Server.MapPath(imgPath))
Dim oGraphic As Graphics = Graphics.FromImage(oBitmap)
Dim frontColorBrush As New SolidBrush(Color.White)
Dim oFont As New Font(FONT_NAME, 30)
Dim oInfo() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders
Dim oEncoderParams As New EncoderParameters(1) 'jpeg
Dim xOffset As Single = Math.Round((oBitmap.Height - oFont.Height) / 2, MidpointRounding.ToEven)
Dim oPoint As New PointF(275.0F, xOffset + 10)
oEncoderParams.Param(0) = New EncoderParameter(Encoder.Quality, 100L)
oGraphic.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
oGraphic.DrawString(oText, oFont, frontColorBrush, oPoint)
oBitmap.Save(Response.OutputStream, oInfo(1), oEncoderParams)
Response.Output.Write(oBitmap)
oBitmap.Dispose()
oGraphic.Dispose()
Response.Flush()
Catch ex As Exception
End Try
End Sub
Armado con esta información, quiero saber si es posible que AsyncPostBack actualice el CSS para que la imagen cambie cuando haga clic en el Botón2.Estoy abierto a sugerencias y/o comentarios del tipo "esa es la forma estúpida/difícil de hacer esto, prueba esto...".
¡Gracias chicos!
Solución
Dado que usted ha dicho que está abierto a sugerencias ... ¿por qué se establece en hacer esto con la AsyncPostBack y CSS? ¿Por qué no acaba de tener un evento onclick javascript para cambiar dinámicamente la imagen al hacer clic en Button2?
editar (en respuesta a enviar a continuación):
No habría ningún segundo palo (si eso es lo que quiere decir con parpadeo): puede seguir utilizando el AsyncPostBack para cualquier otra cosa que está haciendo, y luego tener un adicional de función javascript disparó onclick que haría algo así
document.getElementById('headerimg').src='2.jpg';
Esto cambiaría la imagen de nuevo archivo de origen sin ninguna actualización de la página.