使用javascript根据内容放置位置为元素应用Css

时间:2017-06-01 11:24:18

标签: javascript html css

我有html内容,我需要根据内容中的位置来应用css。

示例:我有两个页面,但两个页面都加载了相同的js文件。我需要根据内容放置位置仅将css应用于一页。

我只需要为第2页的测试内容应用css(通用css)。(id = test在主标签之后)。

仅使用javascript而不是jQuery。

//I need to apply the css for test content only for page2.(id=test have after the main tag).

var contentArea = document.querySelector('.wp-body:not(main >:not(.sample-page)) #test');
    if(contentArea){
      contentArea.style.color = 'red'; //color is dynamic data
    } 
Page1:
<body class="wp-body">
  <main >
      <div class="sample-page"></div>
      <div id="test">
        <span> ABCD</span>
        <span> EFGH</span>
      </div>
  </main>
</body>

Page2: 
<body class="wp-body">
  <main >
      <div>xxx</div>
  </main>
  <div id="test">
    <span> ABCD</span>
    <span> EFGH</span>
  </div>
</body>

1 个答案:

答案 0 :(得分:0)

你需要在body标签中添加类,然后为body.page2或body.page1的子元素编写单独的css规则

.wp-body main #test {} //points only to the #test div on page1
.wp-body > #test {} //points only to the #test div on page2

$(".wp-body main #test").css()  //set the style for #test div on page 1
$(".wp-body > #test").css() // set the style for #test div on page 2