简体   繁体   English

动态更改CSS href链接

[英]Change CSS href link Dynamiclly

<link href="CSS/make.css" rel="stylesheet" />

This an external css file for a page named "Default.aspx" which is located in "Root/Pages" directory. 这是一个名为"Default.aspx"的页面的外部css文件,该文件位于"Root/Pages"目录中。

so In "Root/Pages" we will have these: 因此,在"Root/Pages" ,将具有以下内容:

Default.aspx
CSS/make.css

It will work fine if I launch Default.aspx from current location, But user can change the directory of Default.aspx from main page. 如果从当前位置启动Default.aspx ,它将可以正常工作,但是用户可以从主页更改Default.aspx的目录。 Then in Code-Behind I will copy all of Pages contents into another directory. 然后,在“代码隐藏”中,我将所有Pages内容复制到另一个目录中。

Just think I will copy Default.aspx and CSS folder from Root/Pages to Root/Backup and try to launch Default.aspx from new location. 试想一下,我会将Default.aspx和CSS文件夹从Root/Pages复制到Root/Backup然后尝试从新位置启动Default.aspx。 In this situation it can not read and load external css file! 在这种情况下,它无法读取和加载外部CSS文件!

How can I change css href link dynamically from its container page's location? 如何从其容器页面的位置动态更改css href链接?

For example changing href="CSS/make.css" to href="BackUp/CSS/make.css" . 例如,将href="CSS/make.css"更改为href="BackUp/CSS/make.css"

After some research I found that I should use Global and URL Routing, but I did not get any working result. 经过一些研究,我发现我应该使用全局和URL路由,但是没有得到任何有效的结果。

If you put the css file in the root directory then refer to it using: 如果将css文件放在根目录中,请使用以下命令进行引用:

<link href="/make.css" rel="stylesheet" />

It should now work even when you move your Default.aspx to another location. 现在,即使将Default.aspx移到另一个位置,它也应该可以工作。 The downside to this is that it can clutter your root directory if you plan to use it for multiple different pages with different CSS files. 缺点是,如果您打算将其用于具有不同CSS文件的多个不同页面,则它可能会使根目录混乱。

Let me know if it works and if I am understanding your question right. 让我知道它是否有效,以及我是否理解您的问题正确。

function DynamicURL()
    {  
    var URL='CSS/make.css';
    var BackUp ='BackUp/';
    if (Your condition when it changes directory)
    URL = Backup + URL;

    document.getElementById('Field').href= URL;
    }

Don't forget to set ID to your link href field. 不要忘记将ID设置为您的链接href字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM