有没有重新加载css而不重新加载页面的简单方法? [英] Is there an easy way to reload css without reloading the page?

查看:1378
本文介绍了有没有重新加载css而不重新加载页面的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个预览功能生成一个页面内的CSS编辑器,它将重新加载样式表并应用它,而不需要重新加载页面。

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?

推荐答案

在编辑页面上,而不是将正常方式(使用< link> 标记),将其全部写入< style> 标记。编辑 innerHTML 属性将自动更新页面,即使没有到服务器的往返。

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 innerHTML property of that will automatically update the page, even without a round-trip to the server.

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

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

使用jQuery的Javascript:

The Javascript, using jQuery:

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

这应该是!

如果你想要真的想,附加功能到textarea键下,虽然你可以得到一些不必要的副作用(页面将不断变化,你输入)

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)

编辑:测试并正常工作(至少在Firefox 3.5中,虽然应该与其他浏览器兼容)。请参见此处的演示: http://jsbin.com/owapi

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

这篇关于有没有重新加载css而不重新加载页面的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆