什么是执行CSS滚动的首选方法? [英] What is the preferred way to do a CSS rollover?
问题描述
在HTML中设置翻转效果时,在CSS和JavaScript中执行此操作有什么好处(或陷阱)?是否有任何性能或代码可维护性问题,我应该注意到任何一种方法?
When setting up a rollover effect in HTML, are there any benefits (or pitfalls) to doing it in CSS vs. JavaScript? Are there any performance or code maintainability issues I should be aware of with either approach?
推荐答案
CSS是很好的翻牌。它们的实现基本上是使用:hover
伪选择器。这里有一个非常简单的实现:
CSS is fine for rollovers. They're implemented basically using the :hover
pseudo-selector. Here's a really simple implementation:
a{
background-image: url(non-hovered-state.png);
}
a:hover{
background-image: url(hovered-state.png);
}
有几件事你需要注意:
- IE6仅支持
:hover
< a& code>标签
- 在CSS中指定但未在页面上使用的图片将不会立即加载(意味着翻转状态可能需要一秒钟才会显示)
< a>
-tags-only限制通常没有问题,往往希望滑动可点击。后者是一个更多的问题。有一种名为 CSS Sprites 的技术可以防止此问题,您可以找到一个技术示例在使用中无预加载滚动。
The <a>
-tags-only restriction is usually no problem, as you tend to want rollovers clickable. The latter however is a bit more of an issue. There is a technique called CSS Sprites that can prevent this problem, you can find an example of the technique in use to make no-preload rollovers.
这很简单,核心原则是你创建一个大于元素的图片,将图片设置为背景图片,并使用 background-position
所以只有你想要的位是可见的。这意味着要显示悬停状态,您只需要重新定位背景 - 没有额外的文件需要加载。这里是一个快速和脏的例子(这个例子假设你有一个元素20px高,和一个背景图像包含悬浮和非悬浮状态 - 一个在另一个之上(所以图像是40px高)): / p>
It's pretty simple, the core principle is that you create an image larger than the element, set the image as a background image, and position it using background-position
so only the bit you want is visible. This means that to show the hovered state, you just need to reposition the background - no extra files need to be loaded at all. Here's a quick-and-dirty example (this example assumes you have an element 20px high, and a background image containing both the hovered and non-hovered states - one on top of the other (so the image is 40px high)):
a{
background-image: url(rollover-sprites.png);
background-position: 0 0; /* Added for clarity */
height: 20px;
}
a:hover{
background-position: 0 -20px; /* move the image up 20px to show the hovered state below */
}
使用这种sprites技术意味着你将无法使用alpha透明PNG与IE6(作为唯一的方式IE6必须渲染透明的PNG正确使用一个特殊的图像过滤器,不支持 background-position
)
Note that using this 'sprites' technique means that you will be unable to use alpha-transparent PNGs with IE6 (as the only way IE6 has to render alpha-transparent PNGs properly uses a special image filter which don't support background-position
)
这篇关于什么是执行CSS滚动的首选方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!