1

将动态 CSS 代码注入文档以便可以在运行时预览所做的更改的最佳方法是什么?

我在 HTML 页面中有一个 TextArea,我将在其中键入 CSS 代码。我想从文本区域更新页面的样式。这是我目前使用的方法。

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic CSS Experiments</title>
    <meta charset=utf-8 />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <style id="dynamic-css" type="text/css"></style>
    <!--[if IE]>
        <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        jQuery(function ($) {
            var styleTag, textArea;
            styleTag = $("#dynamic-css");
            textArea = $("#css-ta");
            textArea.on('keydown', function () {
                styleTag.html(textArea.val())
            });
        });
    </script>
</head>
<body>
    <textarea name="css" id="css-ta" cols="30" rows="10"></textarea>
    ...
</body>
</html>

这是最好的方法吗?还有其他聪明的方法吗?

4

4 回答 4

2

尝试这样的事情来限制更新的数量。

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic CSS Experiments</title>
    <meta charset=utf-8/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <style id="dynamic-css" type="text/css"></style>
    <!--[if IE]>
        <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        jQuery(function ($) {
            var styleTag, textArea, active=true, threashold=100;
            styleTag = $("#dynamic-css");
            textArea = $("#css-ta");
            textArea.on('keydown', function () {
                if (active===true) {
                    active = false;
                    setTimeout(function(){
                        styleTag.html(textArea.val());
                        active = true;
                    }, threashold);
                }
            });
        });
    </script>
</head>
<body>
<textarea name="css" id="css-ta" cols="30" rows="10"></textarea>
...
</body>
</html>
于 2013-05-11T17:44:17.633 回答
1

我应该认为“最好的”方法对于每种情况都是独一无二的。

根据您的脚本,向 keydown 事件添加限制可能很有用,因此您可以减少样式的更新次数并提高性能。

请参阅 $.throttle 或 $.debounce https://code.google.com/p/jquery-debounce/ - 实施示例

于 2013-05-11T17:37:52.357 回答
0

另外,请考虑 jQuery 函数:.addClass().removeClass()动态应用 CSS 样式。

于 2013-05-11T17:40:10.147 回答
0

一个更改进的版本是这样的:

    jQuery(function ($) {
        var styleTag, textArea;
        var kI;
        styleTag = $("#dynamic-css");
        textArea = $("#css-ta");
        textArea.on('keyup', function () {
            if (kI !== undefined) {
                 clearTimeout(kI);
            }
            kI = setTimeout(function() {
               styleTag.html(textArea.val());
            },1000);
        });
    });

这会在 keyup 事件上设置一个超时(keyup 发生在 keydown 之后,并防止有人按住键重复),在事件发生后触发 1 秒。每次事件发生时,倒计时都会重置。如果倒计时运行,您的 CSS 会更新。

这避免了样式块内容的过多重写。

于 2013-05-11T17:41:15.790 回答