96

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

4

13 回答 13

113

可能不适用于您的情况,但这是我用于重新加载外部样式表的 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);
    });
}
于 2010-01-08T00:01:59.893 回答
51

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

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

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

使用 jQuery 的 Javascript:

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

应该就是这样!

如果您想真正花哨,请将功能附加到 textarea 上的 keydown,尽管您可能会得到一些不需要的副作用(页面会在您键入时不断变化)

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

于 2010-01-07T23:44:01.697 回答
15

绝对没有必要为此使用 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 += "";
    }
}
于 2017-04-01T20:19:19.960 回答
9

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

于 2011-07-10T00:15:43.023 回答
8

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

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

或扩展:

for (var link of document.querySelectorAll("link[rel=stylesheet]")) {
  link.href = link.href.replace(/\?.*|$/, "?" + Date.now())
}
于 2017-05-16T20:24:27.027 回答
6

另一种 jQuery 解决方案

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

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

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

var reloadCSS = function() {
  $('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};
于 2014-04-07T20:05:04.173 回答
4

基于以前的解决方案,我用 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);

图片来自火狐:

在此处输入图像描述

它有什么作用?

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

于 2014-09-01T11:57:46.967 回答
0

我现在有这个:

    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();
    } );

在您的页面中使用 id 为 changeCss 的任何元素添加一个带有新 css url 的 href 属性。和一个带有起始 css 的链接元素:

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

<img src="click.jpg" id="changeCss" href="css2.css?t=">
于 2014-11-04T11:28:23.373 回答
0

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

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

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)();
于 2016-03-23T15:29:46.650 回答
0

以一种简单的方式,您可以使用rel="preload"代替rel="stylesheet"

<link rel="preload" href="path/to/mystylesheet.css" as="style" onload="this.rel='stylesheet'">
于 2017-09-18T07:46:22.750 回答
0

简单,如果你使用 php 只需在 css 的末尾附加当前时间,比如

<link href="css/name.css?<?php echo 
time(); ?>" rel="stylesheet">

所以现在每次你重新加载它是什么时,时间都会改变,浏览器认为它是一个不同的文件,因为最后一点一直在变化......你可以对任何文件执行此操作你强制浏览器总是使用你想要的任何脚本语言刷新

于 2019-07-23T07:26:32.233 回答
0

由于这个问题已在 2019 年的 stackoverflow 中显示,因此我想使用更现代的 JavaScript 添加我的贡献。

具体来说,对于非内联的 CSS 样式表——因为原始问题已经涵盖了这一点,不知何故。

首先,请注意我们仍然没有可构造样式表对象。但是,我们希望它们能尽快落地。

同时,假设以下 HTML 内容:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link id="theme" rel="stylesheet" type="text/css" href="./index.css" />
    <script src="./index.js"></script>
  </head>
  <body>
    <p>Hello World</p>
    <button onclick="reload('theme')">Reload</button>
  </body>
</html>

我们可以有,在index.js

// Utility function to generate a promise that is 
// resolved when the `target` resource is loaded,
// and rejected if it fails to load.
//
const load = target =>
  new Promise((rs, rj) => {
    target.addEventListener("load", rs, { once: true });
    target.addEventListener(
      "error",
      rj.bind(null, `Can't load ${target.href}`),
      { once: true }
    );
  });


// Here the reload function called by the button.
// It takes an `id` of the stylesheet that needs to be reloaded
async function reload(id) {
  const link = document.getElementById(id);

  if (!link || !link.href) {
    throw new Error(`Can't reload '${id}', element or href attribute missing.`);
  }

  // Here the relevant part.
  // We're fetching the stylesheet from the server, specifying `reload`
  // as cache setting, since that is our intention.
  // With `reload`, the browser fetches the resource *without* first looking
  // in the cache, but then will update the cache with the downloaded resource.
  // So any other pages that request the same file and hit the cache first,
  // will use the updated version instead of the old ones.
  let response = await fetch(link.href, { cache: "reload" });

  // Once we fetched the stylesheet and replaced in the cache,
  // We want also to replace it in the document, so we're
  // creating a URL from the response's blob:
  let url = await URL.createObjectURL(await response.blob());

  // Then, we create another `<link>` element to display the updated style,
  // linked to the original one; but only if we didn't create previously:
  let updated = document.querySelector(`[data-link-id=${id}]`);

  if (!updated) {
    updated = document.createElement("link");
    updated.rel = "stylesheet";
    updated.type = "text/css";
    updated.dataset.linkId = id;
    link.parentElement.insertBefore(updated, link);

    // At this point we disable the original stylesheet,
    // so it won't be applied to the document anymore.
    link.disabled = true;
  }

  // We set the new <link> href...
  updated.href = url;

  // ...Waiting that is loaded...
  await load(updated);

  // ...and finally tell to the browser that we don't need
  // the blob's URL anymore, so it can be released.
  URL.revokeObjectURL(url);
}
于 2019-12-04T13:11:26.023 回答
-1

是的,重新加载 css 标签。并记住使新 url 唯一(通常通过附加随机查询参数)。我有代码可以做到这一点,但现在没有。稍后会编辑...

编辑:太晚了... harto 和 nickf 打败了我 ;-)

于 2010-01-07T23:35:56.247 回答