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

标签 javascript html css

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

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

我只需要为 page2 的测试内容应用 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>

最佳答案

你需要在body标签中添加class,然后为body.page2或body.page1的 child 写单独的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

关于javascript - 使用 javascript 根据内容放置位置为元素应用 Css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44306196/

相关文章:

javascript - 我在哪里可以找到 angularjs typescript 的 api 引用?

css - body 和内容的不同过渡

html - 如何在div中的列表两侧放置相等大小的边框

html - 使用 HTML 表单提交对象的 JSON 数组

javascript - 如何将 this.props.children 传递给 Textarea

javascript - 代码有问题

javascript - <select> 标签未发布到 MySql 数据库

javascript - 想要按钮 onClick 到 getDay 网页

javascript - 将相同的函数应用于多个元素(按顺序)

javascript - 在没有表格标签的情况下,创建一个具有固定标题和第一列的表格