翻转图像

时间:2012-04-04 16:27:22

标签: javascript html

您好我正在为我正在处理的网站尝试简单的翻转图像。当我在firefox中测试效果时,鼠标悬停效果会移动网页上的其他元素。关于如何解决这个问题的任何建议?

<head>
<script type="text/javascript">
if (document.images) {
    img1 = new Image();
    img1.src = "training2.png";
} </script></head>

<body>
<script type="text/javascript">
function rollover(name, filename)
{
    var fullpath = '' + filename;
    document.images[name].src = fullpath; }
    </script>
<div id="trainingbutton"><a href="#" onmouseover="rollover('button1','training2.png');" onmouseout="rollover('button1','training.png')">
<img src="training.png" name="button1" border="0" alt="training"  /></a></div></body>

2 个答案:

答案 0 :(得分:1)

我不会使用javascript来翻转图像,只需创建一个包含正常状态和悬停状态的精灵,然后使用css的hover属性,你可以移动背景位置。

这样的事情:

<a class="rollover">Link</a>

然后是风格:

a.rollover
{
    background-image:url('/images/background.png');
    background-position:top left;
}

a.rollover:hover
{
    background-position:bottom left;
}

此方法也不必在翻转时下载图像,因为它是作为初始请求的一部分下载的

答案 1 :(得分:1)

前一个人回答;精灵是要走的路。它需要预先加载“悬停”图像;它是纯粹的CSS。

示例(图像链接翻转):

HTML:

<a href="#" class="mysprite">Join Newsletter</a>

将非悬停状态和悬停状态图像放在一个画布上。如果每个“图像”高度为20px,则两个堆叠的图像将为40px。因此,为了显示底部图像,您只需背景向上移动20px(因此在下面的悬停状态下为-20px)

CSS:

.mysprite {
    display: block;
    width: 100px;
    height: 20px;
    background: url('mysprite.png') no-repeat;
    background-position: 0 0; /* technically not neccesary, but illustrates the example */
    text-indent: -9999px; /* eliminates the link text so only the background image shows */
    font: 0px; /* eliminates IE displaying the text despite text-indent */

}

.mysprite:hover {
   background-position: 0 -20px;
}

基本上,你创建一个“面具”,你可以从中移动背景图像,以显示你想要的内容。

相关问题