简体   繁体   English

编辑特定的内联<style> 's via javaScript

[英]Editing specific inline <style> 's via javaScript

I have: 我有:

<style id=inlinestyle>
    .container {
        height: 0;
    }
    .container li {
        height: 10px;
    }
    .container li a {
                 color: pink;
    }
</style>

I would like to be able to target and edit `.container li a' without losing the other styles i have. 我希望能够定位和编辑`.container li a'而不会丢失我拥有的其他样式。

 $('#inlinestyle').html('#poop { color: red }');

This won't work as i will lose everything in there. 这将行不通,因为我将在那里失去一切。

Worth mentioning that i'll have an infinity amount of elements being created so inline styles aren't an option. 值得一提的是,我将创建无限数量的元素,因此无法选择内联样式。

wouldn't it just be better to target the element you want to modify ? 定位要修改的元素会更好吗?

$('#poop').css('color','red');

And if you'd like to add more than one property to the css of that precise element just do: 如果您想为该精确元素的css添加多个属性,请执行以下操作:

$('#poop').css({
    'color' : 'red',
    'font-size' : '16px',
    ......
});
$('#inlinestyle').append('.container li a { /* css here */}');
$('.container li a').css("color", "blue");

Try something like $('#inlinestyle').append(' #poop { color: red; }'); 试试$('#inlinestyle').append(' #poop { color: red; }'); or $('#poop').css('color', 'red'); $('#poop').css('color', 'red');

$('#inlinestyle').append('#poop { color: red }');

You shouldn't edit your original CSS via JS, but add the desired rules the element which is to get styled: 您不应该通过JS编辑原始CSS,而是将所需的规则添加到要设置样式的元素中:

/* What about: */
$( '.container li a' ).css( 'property', 'value' );
/* or */
$( '.container li a' ).css( {
    'property1': 'value1',
    'property2': 'value2'
} );

This should be more or less what you're looking for: http://jsfiddle.net/ZH9JW/2/ 这应该或多或少是您所寻找的: http : //jsfiddle.net/ZH9JW/2/

The problem with this is that it's a very rigid regular expression; 问题在于这是一个非常严格的正则表达式; one space more or less, or no newline characters and the regular expression will fail. 一个或多个空格,或者没有换行符,并且正则表达式将失败。 You can solve this ofcourse, but then you're starting to build a CSS parser. 您当然可以解决此问题,但是随后您将开始构建CSS解析器。 I recommend against using my solution. 我建议不要使用我的解决方案。

Maybe this is something you could use? 也许这是您可以使用的东西? It's probably faster than $("#poop").css("color", "red"); 它可能比$("#poop").css("color", "red");更快$("#poop").css("color", "red"); if you're creating so many elements, but a bit of a hack: 如果您要创建许多元素,但是有点hack:

var newStyle = $("<style/>").html(".container li a { color: red }");
$("body").append(newStyle);

This style element should by the way ideally be in the DOM after your original style element, or have more specific CSS. 理想情况下,此style元素应位于原始style元素之后的DOM中,或者具有更特定的CSS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM