在CSS中使用Javascript [英] Using Javascript in CSS

查看:132
本文介绍了在CSS中使用Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在CSS中使用Javascript?

Is it possible to use Javascript inside CSS?

如果是,您能给出一个简单的例子吗?

If it is, can you give a simple example?

推荐答案

IE和Firefox都包含从CSS执行JavaScript的方法。正如Paolo所提到的,IE中的一种方法是 expression 技术,但也有更模糊的 HTC行为,其中包含您的脚本通过CSS加载。存在一个类似的Firefox技术,使用 XBL 。这些技术并不直接从CSS中强制JavaScript ,但效果是一样的。

IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.

使用如下的CSS规则:

Use a CSS rule like so:

body {
  behavior:url(script.htc);
}

并且在该script.htc文件中有如下:

and within that script.htc file have something like:

<PUBLIC:COMPONENT TAGNAME="xss">
   <PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
   function main() 
   {
     alert("HTC script executed.");
   }
</SCRIPT>

HTC文件执行 main()函数对 ondocumentready (指HTC文档的准备就绪)

The HTC file executes the main() function on the event ondocumentready (referring to the HTC document's readiness.)

Firefox支持使用XBL执行类似的XML脚本执行攻击。

Firefox supports a similar XML-script-executing hack, using XBL.

使用如下的CSS规则:

Use a CSS rule like so:

body {
  -moz-binding: url(script.xml#mycode);
}

并在您的script.xml中:

and within your script.xml:

<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">

<binding id="mycode">
  <implementation>
    <constructor>
      alert("XBL script executed.");
    </constructor>
  </implementation>
</binding>

</bindings>

构造函数标签中的所有代码都将被执行(一个好主意,

All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)

在这两种技术中,除非CSS选择器匹配文档中的元素,否则代码不会执行。通过使用 body ,它将在页面加载时立即执行。

In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body, it will execute immediately on page load.

这篇关于在CSS中使用Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆