search
HomeWeb Front-endJS TutorialWhatever:hover makes IE support rich pseudo-classes without javascript_javascript skills

这很酷,因为这使你可以仅通过 css来对表格行(

)应用鼠标滑过事件(mouseover)时的特殊效果。然而,万恶的IE,对 :hover伪类顶多只提供了有限的支持,具体支持的程度要取决于你的IE浏览器的具体版本。

Whatever:hover 是一个小小的脚本,它可以迅速、自动地为IE6,IE7,IE8添加标准的 :hover、:active 和:focus 伪类支持。第三版引入了 ajax 支持,意味着通过 javascript动态添加到文档中的任意html元素也同样可以在IE中响应 :hover、:active 和 :focus 样式。

 

如果你已经对使用 whatever:hover 很熟练,现在只是想下载它,你可以直接跳转到获取最新版本。而对于其它想深入了解它的人,请继续阅读。

使用方法

你只需要将 whatever:hover 链接到 body 元素就可以了。注意这里的 behavior 属性中的 URL 是相对于 html 文件的,而不是像背景图片地址一样是相对于 css 文件的路径。

<SPAN style="COLOR: #a31515">body </SPAN>{ <SPAN style="COLOR: red">behavior</SPAN>: <SPAN style="COLOR: blue">url("csshover3.htc")</SPAN>; }

工作原理

所有的浏览器都提供了一些方法,让你用 javascript 查询样式表中定义好的规则或者动态地插入新规则。正常情况下,IE对所有它不支持的规则返回 “unknown”。例如:一条关于 “div p:first-child” 的规则将会被改成 "divp:unknown”, 而一条关于 "p a[href]” 的规则将整体地作为 "unknown" 返回。幸运的是 IE 把 :hover伪类认为是它支持的样式规则,并且会将它保持原样。

IE 还支持所谓的行为(behaviors),不仅包括预定义的功能比如动态加载内容或者持续数据存储,也包括你可以在一个后缀为 .htc 或者 .hta 为的文件中创建的自定义行为。这些行为通过 css 实现与 html 节点关联,并“增强”这些被指定行为中的样式选择器选中的节点。

综上所述,创建一个行为来查找样式表中 IE 不支持的元素,并以一些其它手段“欺骗”影响的到元素让它们应用样式表中关联的样式。这个复杂的操作中包含的步骤大致可以描述为:

  • 在所有的样式表中搜索 IE 不支持的 :hover 伪类规则;
  • 插入一条 IE 支持的,例如带 class 名称的新规则;
  • 最后,设置脚本事件来切换目标元素的 class 名称。

通过这种方式,:hover、:active 和 :focus 就可以得到(IE 的)支持了。而作为开发人员,你除了包含这个行为以外不需要做任何事。所有的工作都将自动完成。

与第1版和第2版比较,第3版对动态加入的 html (ajax) 也同样支持。另外还有一个改动是原来第1版和第2版采用的是在页面加载事件中主动搜索影响到的元素,而在第3版中改为借助表达式(expressions)让节点自己回调。关于这部分你可以阅读带注释的版本获取更多细节。

示例:菜单效果

:hover 一个很常见的用途就是用列表创建菜单系统。用这个行为来创建一个两级的菜单系统是再容易不过的事情了。例如,如果你从 suckerfish dropdown (一个带有下拉菜单的网页,关于这个页面和效果的描述,参见 A List Apart article)上把 javascript 删除掉了,它仍然能正常工作。

但是多级的菜单需要做不同的处理。这是由于 IE 不支持子选择符 ‘>',子选择符可以完美地显示下级子菜单,而不是连更深层的菜单一起显示出来。

<SPAN style="COLOR: #a31515">li:hover > ul </SPAN>{ <SPAN style="COLOR: green">/* 在 IE 下无效 */ </SPAN>}

有一种可供选择的方法可以只使用简单的子孙选择符来模拟这种行为(主要是针对 IE)。还有种不太成熟的方法是应用多个类定义,但是更简单的方法是利用 CSS 选择符的不同优先级(specificity).每一条 css 规则都有特定的重要等级,这个等级可以简单地根据一条规则中的不同元素来计算。以元素名称为基准值 “1″,类、伪类和属性选择符重要性(权重)为 “10″,然后元素 id 为 “100″。比如下面的例子。

<SPAN style="COLOR: #a31515">ul ul </SPAN>{ <SPAN style="COLOR: red">display</SPAN>:<SPAN style="COLOR: blue">none</SPAN>; }<BR><SPAN style="COLOR: #a31515">li:hover ul </SPAN>{ <SPAN style="COLOR: red">display</SPAN>:<SPAN style="COLOR: blue">block</SPAN>; }

这样做能够生效的原因,就是选择符的优先级不同。第一条规则只包含两个元素名称,这样它的权重值(优先级)就是2。第二条规则也包含两个元素名称,但是 :hover 伪类的权重值(优先级)是10,所以加起来的值就是12。由于第二条规则比第一条规则优先,因此被鼠标滑过的 li 元素内部的ul 将被显示。

那么这个对于解决 >子选择符的问题有什么帮助呢?是这样,如果一条权重值(优先级)为12的规则定义所有的子菜单都要显示,我们只需要创建一条权重值(优先级)大于12的规则来把下一级的菜单隐藏起来。然后,那个菜单又需要另一条优先级更高的规则来显示,一直循环下去。对于3级的导航来说,需要的 css代码短得让人意外:

<SPAN style="COLOR: green">/* 2 和 13 */<BR></SPAN><SPAN style="COLOR: #a31515">ul ul</SPAN>, <SPAN style="COLOR: #a31515">li:hover ul ul </SPAN>{ <SPAN style="COLOR: red">display</SPAN>:<SPAN style="COLOR: blue">none</SPAN>; }<BR><SPAN style="COLOR: green">/* 12 和 23*/<BR></SPAN><SPAN style="COLOR: #a31515">li:hover ul</SPAN>, <SPAN style="COLOR: #a31515">li:hover li:hover ul </SPAN>{ <SPAN style="COLOR: red">display</SPAN>:<SPAN style="COLOR: blue">block</SPAN>; }

这种方式可以无需附加任何类样式实现无限级嵌套菜单(4级或更多级需要需要继续添加更多规则)。

脚本事件的性能优化

现在还剩下一件事需要考虑。.htc 文件在所有样式表文件中搜索 :hover 规则,并且按照 css 文件的定义对所有它认为需要用脚本处理停留效果的元素附加鼠标滑过和移出事件。为了找出这些(被影响的)元素,所有去掉 :hover 伪类选择到的元素以及被 :hover 伪类修饰的元素本身,都会被选择并且进行处理。一条类似这样的规则

<SPAN style="COLOR: #a31515">#menu li:hover ul </SPAN>{ ... }

…将会被调整成下面这样来查找所有可能需要响应鼠标滑过事件的元素:

<SPAN style="COLOR: #a31515">#menu li </SPAN>{ ... }

很显然这会选中整个菜单中的每一个

  • 元素,并对其中一大堆不需要鼠标事件(在当前情况下)的元素附加事件。这个问题可以很轻松地得到解决,我们可以对包含子菜单的列表元素添加一个类样式,比如 "folder"。这样一来,调整(去除:hover)之后的样式规则变成了
    <SPAN style="COLOR: #a31515">#menu li.folder </SPAN>{ ... }

    …可以高效地直接选中那些真正需要事件的元素。缺点是为了改善脚本的性能,你需要添加一个类样式(这个类样式的添加纯粹是为了视觉效果,而且放弃了li:hover 方式实现菜单的通用性)。但是,从另一个角度考虑的话,也许你反正也要用一个类来把这些列表元素与普通元素区别开来,那就无所谓了。

    为了直观地说明上述问题,请查看综合示例。希望你喜欢。

    文件下载及更新说明:

    文件下载:

    Version 3.11 (:hover, :active and :focus) 
     
    (:hover, :active 和 :focus)
    Minified, 2.8K (right click & save) | commented, 9.7K | both, zipped

    Version 1.42.060206 (:hover and :active) download | view
    Version 2.02.060206 (1.42 and :focus) download | view

    说明:

    说明1:如果在使用 whatever:hover 的过程中遇到问题,请 让我知道!  由于第3版比较新,可能会存在一些无法预知的问题。

    说明2:确保你的web服务器把 htc 文件按照 text/x-component 的 mime类型发送。关于这方面的更多信息,可以参阅 Aldo的个人博客。如果你的主机支持 .htaccess 文件,可以添加下面这行代码:

    <SPAN style="COLOR: #a31515">AddType text</SPAN>/<SPAN style="COLOR: #a31515">x-component .htc</SPAN>

    说明3:第三版支持在 IE6 以上版本中使用 :hover 和 :active,对 IE7 和 IE8 还支持:focus。由于表达式(expression)在 IE8 标准模式下不支持,所以 whatever:hover 只在 IE8 的怪异模式(Quirks Mode) 下运行。实际上在 IE8 标准模式中也根本不需要这个脚本了。

    说明4:如果使用这个脚本之后网页变慢,请尝试对更加具体的选择符运用 :hover伪类,比如添加元素名称、使用元素id,或者类名称。例如:"div#someId li.group:hover”, 而不要只用".group:hover”。这样能够很大程度上减少搜索和解析时间,并能减少需要应用的事件。请阅读 获得更多信息。

    참고 5: 버전 2는 A, INPUT 및 TEXTAREA 요소로 제한되는 :focus 의사 클래스도 지원합니다. 그러나 "input:focus"와 같은 선택기는 IE의 스타일시트 개체에 의해 "input:unknown"으로 반환되므로 스크립트는 이러한 "unkonwn" 규칙을 기반으로 포커스 획득 및 포커스 손실 이벤트를 첨부합니다. 이 문제는 다른 의사 클래스에도 존재합니다. 브라우저에서 인식됩니다. 따라서 버전 2.0을 사용하는 경우 브라우저에서 인식할 수 없는 의사 클래스를 IE의 A, INPUT 및 TEXTAREA 요소에 적용할 수 없습니다. 이는 모두 포커스 스타일로 처리되기 때문입니다. 이 기능이 꼭 필요한 경우 버전 1.4 또는 3.0을 사용하세요.

    Naar Voren(웹 개발에 관한 독일 웹사이트) 메뉴 시스템에 순수 CSS to use:hover 사용에 대해 독일어로 쓴 글이 있습니다. (독일어 버전). 독일어를 모르는 네티즌들은 이 글의 영어 번역본을 참고하세요.

    창의력과 지원을 제공한 Arnoud Berendsen과 Martin Reurings, 내 기사를 출판해 준 Robert Jan Verkade와 Naar Voren의 친구들, 그리고 Eric에게 많은 감사를 드립니다. Meyer 는 이 스크립트에 대한 지원을 제공했으며 그의 책에서 내 웹페이지를 언급했습니다("Eric Meyer Talks CSS(Volume 2) " 6장" - 번역가의 메모 참조).

    저자: peter ned 원문: whatever:hover

    번역자: Xiao Li Daodao 초판: Whatever:hover - IE가 풍부한 의사 클래스를 지원하도록 하기 위해 자바스크립트가 필요하지 않습니다

    재인쇄시 출처를 꼭 밝혀주세요.
    위 파일 스크립트 홈 패키지 다운로드 주소

  • Statement
    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
    From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

    JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

    Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

    Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

    The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

    C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

    JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

    JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

    JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

    The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

    Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

    Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

    Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

    Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools