开发者

How to make the effects of jQuery's $(element).css() persistent?

For example, with a font-size switcher/button, if I use

    $('#container p').css('font-size', '24px');

it works as expected, but if I later add paragraph elements to the container (via ajax, etc), they are not styled with the updated font-size. I am aware that th开发者_JAVA技巧is is the intended behavior of the .css() method. I am simply asking:

What's the proper approach to changing a style for a CSS selector, and making those styles persistent?


Right, well, when you perform that command, it styles all p elements in #container. If you want it to be permanent, you could create a <style /> element and add the CSS stylings there.


To elaborate, you could do something like this:

$(document.head).append('<style>#container p{font-size: 24px;}</style>');


What jQuery does in that line is equivalent to:

<div id='container'>
  <p style='font-size:24px'>a</p>
  <p style='font-size:24px'>b</p>
  <p style='font-size:24px'>c</p>
</div>

For your particular case I'd get one of the stylesheets present in the document, like this:

var stylesheets = document.styleSheets

Which returns an array of styleSheet objects that contain the insertRule method, which you can use to add your new (permanent) css rule.

Cheers!


You cannot add the style directly w/ JavaScript, but you can however do this:

<div id="wrapper">
  <div id="paragraph1">blah</div>
  <div id="paragraph2">you</div>
</div>

and

$("#wrapper").css...

This way any paragraph you add to the wrapper will have the new font size...


Well you are adding style to exiting elements only, there is no way for jquery to know about the new elements.


The problem is probably that you are destroying the element upon which you have the style.

If you are bringing in via AJAX a replacement for #container, then all of the content will get destroyed and replaced with the new content. All of the <p> tags you added the style to will no longer exist, and it will need to be repeated on the newer entry.

What you could try is creating a class definition on the fly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜