简体   繁体   English

如何始终删除特定元素的内联样式?

[英]How to always remove inline style for specific element?

How to always remove inline style for specific element? 如何始终删除特定元素的内联样式?

I use this code to remove my style : 我使用以下代码删除我的样式:

jQuery('.myelement').removeAttr('style');

but it's not work probably because another js code is adding inline style after me code to remove it. 但是它不起作用,可能是因为另一个js代码在我的代码后添加了内联样式以将其删除。 There is no .js file after my file is called. 调用我的文件后没有.js文件。

I know I can edit the .js file from the photo plugin but if I update the plugin, I will loose my changes. 我知道我可以从照片插件中编辑.js文件,但是如果更新插件,则会丢失更改。

How can I write in jQuery something to tell that this element will never have inline style? 我如何在jQuery中写一些东西来告诉这个元素永远不会有内联样式?

To ensure an items style is always empty, even if some other code runs after yours you can use a mutation observer to reset the style whenever the style attribute of the node changes, like this 为了确保项目样式始终为空,即使在您的项目之后运行其他代码,您也可以在节点的样式属性更改时使用变异观察器重置样式,例如

 let element = document.querySelector(".myelement"); let observer = new MutationObserver((m) => { if (element.style.length > 0) { element.style = {}; } }); observer.observe(element, { attributes: true, attributeFilter: ["style"] }); // now this wont do anything element.style.backgroundColor = "red"; 
 <div class="myelement"> unicorn </div> 

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

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