开发者

jQuery/javascript - give a style to a specific element

开发者 https://www.devze.com 2023-01-30 11:43 出处:网络
Suppose I have 3 page as below: page 1: <开发者_StackOverflow社区;div id=\"content\"> <div id=\"red\"></div>

Suppose I have 3 page as below:

page 1:

<开发者_StackOverflow社区;div id="content">
    <div id="red"></div>
</div>  

page 2:

<div id="content">
    <div id="blue"></div>
</div>  

page 3:

<div id="content">
    <div id="green"></div>
</div>  

This 3 page are in the same template, so if I add

#content {
    margin-top: 10px;
}

All page will apply this style, If I only want to put this style to page 3, how can I do that?

Generally, we use $('#content > #green').css(...) to point to a element, but can we have something like $('#content < #green') to point to a reversed element and give it some style?


You can use:

$('#green').parent().css(...);

If you want to be completely specific, you can do:

$('#green').parent('#content').css(...);


Or you could create a new style class 'contentClass' which holds the styles for elements with id="content" and apply the style class to red, green, and blue. In this way, content becomes an abstract container with no styles, and the actual styling gets moved where it should.

So in your style sheet:

.contentClass {
  /* Your content styles here /*
}

And on your pages:

<div id="content">
  <div id="red" class="contentClass"></div>
</div>

<div id="content">
  <div id="green" class="contentClass"></div>
</div>

<div id="content">
  <div id="blue" class="contentClass"></div>
</div>


Have you tried $("#content eq(index of element)") ??

0

精彩评论

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