我想用一个预览功能生成一个页面内的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中,虽然应该与其他浏览器兼容)。请参见此处的演示: jsbin/owapi
Edit: tested and works (in Firefox 3.5, at least, though should be fine with other browsers). See demo here: jsbin/owapi
更多推荐
有没有重新加载css而不重新加载页面的简单方法?
发布评论