向文档注入动态CSS

Inject dynamic CSS to a document?

本文关键字:CSS 动态 注入 文档      更新时间:2023-09-26

向文档注入动态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>

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

试试这样做来限制更新的次数。

<!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>

我认为"最好"的方法对每种情况都是唯一的。

根据你的脚本,在keydown事件中添加节流可能是有用的,这样你就可以减少样式的更新次数并提高性能。

看到美元。节流或$.debouncehttps://code.google.com/p/jquery-debounce/-实现示例

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

一个更完善的版本应该是这样的:

    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之后,防止有人重复按下一个键),在事件发生后触发15秒。每次事件发生,倒计时就会重置。如果倒计时结束,你的CSS会更新。

这样可以避免过多地重写样式块的内容。