繁体   English   中英

使用javascript根据内容放置位置将CSS应用于元素

[英]Apply Css for the element based on content placed location using javascript

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

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

我只需要将css(generic css)应用于页面2的测试内容。(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标记,然后为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM