我有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/