将一段代码与所有现有的外部 CSS 隔离
我已经使用教程为我的网站创建了一个小部件。
现在需要将该小部件放入一个复杂的页面中,并在 *、body、ul 和 li 等重要标签上使用现有的 CSS 规则。
有没有办法将此小部件(当前是一个包含 html、css 和 javascript 的单独页面)放入我的网页中,而无需网页在其顶部应用所有自己的 CSS?
I have used a tutorial to create a widget for my site.
This widget now needs to be dropped into a complex page with existing CSS rules on important tags like *, body, ul, and li.
Is there a way to drop in this widget (currently a separate page with html, css, and javascript) into my webpage without the webpage applying all of its own CSS on top?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是使用
iframe
。如果您想要一个嵌入式小部件,最明智的做法是在小部件的标记中内联指定 CSS 属性。这通常是不好的做法,但在这里是正确的做法。
例如,查看 Facebook 个人资料徽章(您需要是 Facebook 用户才能看到它)看起来像:
他们很可能对此进行了大量测试,因此他们在代码中设置的 CSS 属性,我建议也在您的小部件中设置。
The easiest way would be to use an
iframe
.If you want an embedded widget, the wisest thing to do is to specify the CSS properties inline in the widget's markup. It's bad practice usually, but is the right thing here.
Check out for example what the Facebook Profile badge (you need to be a Facebook user to see it) looks like:
They are very likely to have done a lot of testing on this, so the CSS properties they set in their code, I would recommend to set in your widget, too.
可以使用 IFrame 来完成,但我不推荐这样做。 IFrame 很混乱,而且通常不能按预期工作。有些浏览器会阻止它们,有些浏览器根本不支持它们,并且从 IFrame 页面与它们所在的页面进行交互非常困难。
最干净的方法是将小部件包装在一个带有 id(如 widgetwrapper)的额外 div 中。然后为每个 css 规则添加前缀
#widgetwrapper [space]
。这样,小部件中的 CSS 就不会影响页面的其余部分。确保将小部件的 css 放在 css 的最后。如果仍然有页面规则干扰您的小部件,请在小部件 CSS 中覆盖它们。It can be done with an IFrame, but I wouldn't reccomend that. IFrames are messy and they usually don't work as expected. Some browsers block them, some don't support them at all, and interacting with the page they're in from the IFrame page is really hard.
The most clean way is by wrapping the widget in an extra div with an id like widgetwrapper. Then prefix every css rule with
#widgetwrapper [space]
. That way, the css from the widget won't affect the rest of the page. Make sure you put the css for the widget last in the css. If there's still page rules messing with your widget, overwrite them in the widget css.