将动态CSS代码注入文档以便在运行时预览所做更改的最佳方式是什么?
我在一个超文本标记语言页面中有一个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>这是最好的方法吗?有没有其他更好的方法呢?
发布于 2013-05-12 01:44:18
尝试一些类似这样的事情来限制更新的数量。
<!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-12 01:37:52
我认为“最好的”方法对于每种情况都是独特的。
根据您的脚本,在keydown事件中添加节流可能会很有用,这样您就可以减少样式更新的次数并提高性能。
请参见$.throttle或$.debounce https://code.google.com/p/jquery-debounce/ -实现示例
发布于 2013-05-12 01:40:10
另外,考虑jQuery函数:.addClass()和.removeClass(),以便动态地应用CSS样式。
https://stackoverflow.com/questions/16499909
复制相似问题