Home > Web Front-end > CSS Tutorial > How Can I Embed JavaScript Functionality in CSS?

How Can I Embed JavaScript Functionality in CSS?

Mary-Kate Olsen
Release: 2024-12-19 15:52:09
Original
463 people have browsed it

How Can I Embed JavaScript Functionality in CSS?

Embedding JavaScript in CSS

While it's not directly possible to execute JavaScript within CSS, there are creative techniques that allow for similar functionality.

IE: Expression Technique and HTC Behavior

Internet Explorer provides two methods:

  • Expression Technique: Involves creating an expression that evaluates a JavaScript expression. For example:
body {
  color: (function() { return document.getElementById("button").style.color; })();
}
Copy after login
  • HTC Behavior: Utilizes a separate XML file (script.htc) loaded via CSS. Inside the HTC file, JavaScript can be executed.
body {
  behavior:url(script.htc);
}
Copy after login
<PUBLIC:COMPONENT TAGNAME="xss">
   <PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>

<SCRIPT>
  function main() {
    alert("HTC script executed.");
  }
</SCRIPT>
Copy after login

Firefox: XBL

Firefox offers a similar XML-based solution called XBL.

body {
  -moz-binding: url(script.xml#mycode);
}
Copy after login
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">

  <binding>
Copy after login

Important Considerations

  • JavaScript is executed only when the CSS selector matches an element in the document.
  • These techniques are not standardized and may not work in all browsers.
  • They can introduce security implications, so use cautiously.

The above is the detailed content of How Can I Embed JavaScript Functionality in CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template