Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jQuery(或JS)编写CSS以应用于当前和未来的匹配?_Javascript_Jquery_Css - Fatal编程技术网

Javascript 如何使用jQuery(或JS)编写CSS以应用于当前和未来的匹配?

Javascript 如何使用jQuery(或JS)编写CSS以应用于当前和未来的匹配?,javascript,jquery,css,Javascript,Jquery,Css,我想根据屏幕高度动态设置元素的高度$('.selected').css('height',height)和$('.selected')。高度(height)工作,但当另一个元素成为。选中时不受此规则的影响 我真正想做的是这样的事情: var s = $('<style>.selected{height:'+height+'px}</style>').appendTo(document.head); ... // change the height later s.remo

我想根据屏幕高度动态设置元素的高度<代码>$('.selected').css('height',height)
$('.selected')。高度(height)工作,但当另一个元素成为
。选中时
不受此规则的影响

我真正想做的是这样的事情:

var s = $('<style>.selected{height:'+height+'px}</style>').appendTo(document.head);
...
// change the height later
s.remove();
s = $('<style>.selected{height:'+new_height+'px}</style>').appendTo(document.head);
var s = $('<style>.selected{height:'+height+'px}</style>').appendTo(head);
...
// change the height later
s.replaceWith('<style>.selected{height:'+new_height+'px}</style>');
var s=$('.selected{height:'+height+'px}')。appendTo(document.head);
...
//稍后更改高度
s、 删除();
s=$('.selected{height:'+new_height+'px}')。appendTo(document.head);

有更好的方法吗?

您可以使用
document.styleSheets[0].insertRule(“.selected{height:+new_height+“px}”,0)或类似

总的来说,你所做的一切都很好。如果我是你,我会继续引用你的样式元素tho,并将其替换为如下新元素:

var s = $('<style>.selected{height:'+height+'px}</style>').appendTo(document.head);
...
// change the height later
s.remove();
s = $('<style>.selected{height:'+new_height+'px}</style>').appendTo(document.head);
var s = $('<style>.selected{height:'+height+'px}</style>').appendTo(head);
...
// change the height later
s.replaceWith('<style>.selected{height:'+new_height+'px}</style>');
var s=$('.selected{height:'+height+'px}')。appendTo(head);
...
//稍后更改高度
s、 替换为('.selected{height:'+new_height+'px}');

不,这是最好的方法。请注意,如果可能的话,最好修改现有的
style
标记,而不是添加一个新标记来覆盖现有规则?@drachenstern:当我写我的答案时,删除语句不在问题中;)否则,通过某种魔法,我设法复制/粘贴一个代码块,中间缺少一行……DrChansTern:我同意,这是一个奇怪的例子,我无法用魔术复制/粘贴的其他方式来解释。