Javascript 有没有一种简单的方法可以在不重新加载页面的情况下重新加载 css?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2024486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:26:46  来源:igfitidea点击:

Is there an easy way to reload css without reloading the page?

javascriptcssstylesheetreload

提问by Stephen Belanger

I'm trying to make a live, in-page css editor with a preview function that would reload the stylesheet and apply it without needing to reload the page. What would be the best way to go about this?

我正在尝试制作一个带有预览功能的实时页面内 css 编辑器,该功能可以重新加载样式表并应用它而无需重新加载页面。解决这个问题的最佳方法是什么?

采纳答案by nickf

On the "edit" page, instead of including your CSS in the normal way (with a <link>tag), write it all to a <style>tag. Editing the innerHTMLproperty of that will automatically update the page, even without a round-trip to the server.

在“编辑”页面上,不要以正常方式(使用<link>标签)包含您的 CSS,而是将其全部写入<style>标签。编辑该innerHTML属性将自动更新页面,即使没有往返服务器。

<style type="text/css" id="styles">
    p {
        color: #f0f;
    }
</style>

<textarea id="editor"></textarea>
<button id="preview">Preview</button>

The Javascript, using jQuery:

Javascript,使用 jQuery:

jQuery(function($) {
    var $ed = $('#editor')
      , $style = $('#styles')
      , $button = $('#preview')
    ;
    $ed.val($style.html());
    $button.click(function() {
        $style.html($ed.val());
        return false;
    });
});

And that should be it!

应该就是这样!

If you wanted to be really fancy, attach the function to the keydown on the textarea, though you could get some unwanted side-effects (the page would be changing constantly as you type)

如果你真的很喜欢,可以将函数附加到 textarea 上的 keydown,尽管你可能会得到一些不需要的副作用(页面会随着你的输入而不断变化)

Edit: tested and works (in Firefox 3.5, at least, though should be fine with other browsers). See demo here: http://jsbin.com/owapi

编辑:经过测试并有效(至少在 Firefox 3.5 中,但在其他浏览器中应该没问题)。在此处查看演示:http: //jsbin.com/owapi

回答by harto

Possibly not applicable for your situation, but here's the jQuery function I use for reloading external stylesheets:

可能不适用于您的情况,但这是我用于重新加载外部样式表的 jQuery 函数:

/**
 * Forces a reload of all stylesheets by appending a unique query string
 * to each stylesheet URL.
 */
function reloadStylesheets() {
    var queryString = '?reload=' + new Date().getTime();
    $('link[rel="stylesheet"]').each(function () {
        this.href = this.href.replace(/\?.*|$/, queryString);
    });
}

回答by Dan Bray

There is absolutely no need to use jQuery for this. The following JavaScript function will reload all your CSS files:

绝对没有必要为此使用 jQuery。以下 JavaScript 函数将重新加载您的所有 CSS 文件:

function reloadCss()
{
    var links = document.getElementsByTagName("link");
    for (var cl in links)
    {
        var link = links[cl];
        if (link.rel === "stylesheet")
            link.href += "";
    }
}

回答by mcintyre321

Check out Andrew Davey's snazzy Vogue project - http://aboutcode.net/vogue/

查看 Andrew Davey 时髦的 Vogue 项目 - http://aboutcode.net/vogue/

回答by mattdlockyer

One more jQuery solution

另一种 jQuery 解决方案

For a single stylesheet with id "css" try this:

对于 id 为“css”的单个样式表,试试这个:

$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');

Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:

将其包装在具有全局范围的函数中,您可以在 Chrome 中的开发人员控制台或 Firefox 中的 Firebug 中使用它:

var reloadCSS = function() {
  $('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};

回答by flori

A shorter version in Vanilla JS and in one line:

Vanilla JS 中的一个较短版本,并在一行中:

for (var link of document.querySelectorAll("link[rel=stylesheet]")) link.href = link.href.replace(/\?.*|$/, "?" + Date.now())

Or expanded:

或扩展:

for (var link of document.querySelectorAll("link[rel=stylesheet]")) {
  link.href = link.href.replace(/\?.*|$/, "?" + Date.now())
}

回答by LukLed

Based on previous solutions, I have created bookmark with JavaScript code:

基于以前的解决方案,我使用 JavaScript 代码创建了书签:

javascript: { var toAppend = "trvhpqi=" + (new Date()).getTime(); var links = document.getElementsByTagName("link"); for (var i = 0; i < links.length;i++) { var link = links[i]; if (link.rel === "stylesheet") { if (link.href.indexOf("?") === -1) { link.href += "?" + toAppend; } else { if (link.href.indexOf("trvhpqi") === -1) { link.href += "&" + toAppend; } else { link.href = link.href.replace(/trvhpqi=\d{13}/, toAppend)} }; } } }; void(0);

Image from Firefox:

图片来自 Firefox:

enter image description here

在此处输入图片说明

What does it do?

它有什么作用?

It reloads CSS by adding query string params (as solutions above):

它通过添加查询字符串参数来重新加载 CSS(如上面的解决方案):

回答by tibi

i now have this:

我现在有这个:

    function swapStyleSheet() {
        var old = $('#pagestyle').attr('href');
        var newCss = $('#changeCss').attr('href');
        var sheet = newCss +Math.random(0,10);
        $('#pagestyle').attr('href',sheet);
        $('#profile').attr('href',old);
        }
    $("#changeCss").on("click", function(event) { 
        swapStyleSheet();
    } );

make any element in your page with id changeCss with a href attribute with the new css url in it. and a link element with the starting css:

在您的页面中使用 id changeCss 使用 href 属性创建任何元素,其中包含新的 css url。和一个带有起始 css 的链接元素:

<link id="pagestyle" rel="stylesheet" type="text/css" href="css1.css?t=" />

<img src="click.jpg" id="changeCss" href="css2.css?t=">

回答by Christopher Schneider

Another answer: There's a bookmarklet called ReCSS. I haven't used it extensively, but seems to work.

另一个答案:有一个名为ReCSS的书签。我没有广泛使用它,但似乎有效。

There's a bookmarklet on that page to drag and drop onto your address bar (Can't seem to make one here). In case that's broke, here's the code:

该页面上有一个书签可以拖放到您的地址栏上(这里似乎无法创建)。万一坏了,这里是代码:

javascript:void(function()%7Bvar%20i,a,s;a=document.getElementsByTagName('link');for(i=0;i%3Ca.length;i++)%7Bs=a[i];if(s.rel.toLowerCase().indexOf('stylesheet')%3E=0&&s.href)%20%7Bvar%20h=s.href.replace(/(&%7C%5C?)forceReload=%5Cd%20/,'');s.href=h%20(h.indexOf('?')%3E=0?'&':'?')%20'forceReload='%20(new%20Date().valueOf())%7D%7D%7D)();

回答by Gagan

In a simple manner you can use rel="preload"instead of rel="stylesheet".

以一种简单的方式,您可以使用rel="preload"而不是rel="stylesheet"

<link rel="preload" href="path/to/mystylesheet.css" as="style" onload="this.rel='stylesheet'">