HTML5 / CSS3:悬停图像替换

时间:2015-01-12 08:08:15

标签: html5 css3 hover

我已经在Stack Overflow上阅读了多个解决方案,但我仍然找不到我的解决方案。我尝试过添加图片并操作#one:使用CSS进行操作,但没有任何反应。使用图像到这里并操纵#one:使用CSS悬停我得到的结果有限,但他们都错了。原始图像永远不会被替换,替换图像的一条非常细的线条出现在我原始图像的下方。这是我的代码:

HTML5:

<nav>
<p/><p/>
<a id="one" href="form.html"><img src="nav.email.gif" alt="E-Mail Form" width="256px" height="100px"/></a>
</nav> 

CSS3:

#one:hover 
{
background-image: url('nav.email.ani.gif'); 
width:256px; 
height:100px;
}

使用&#34;背景&#34;而不是&#34;背景图像&#34;没有给我什么,使用div标签什么都没给我。我尝试了替换图像的绝对放置,但我所得到的只是一条细线而不是全尺寸图像(即使使用宽度和高度)。提前致谢。

5 个答案:

答案 0 :(得分:1)

建议使用background-imageimg元素的一个解决方案,如:

#imgOne:hover {
  background-image: url('http://placehold.it/200x100');
  width: 256px;
  height: 100px;
}
#imgOne {
  background-image: url('http://placehold.it/400x200');
}
<nav>
  <p/>
  <p/>
  <a id="one" href="form.html">
    <img id="imgOne" src="" alt="E-Mail Form" width="256px" height="100px" />
  </a>

</nav>

答案 1 :(得分:1)

这是另一种选择。

<a id="one" href="form.html>
     <img title="email" src="nav.email.gif" onmouseover="this.src='nav.email.ani.gif'" onmouseout="this.src='nav.email.gif'" />
</a>

答案 2 :(得分:0)

使用Pure css content快速而简单

#one:hover img{ content:url("http://placehold.it/400x200") }
<nav>
  <p/><p/>
  <a id="one" href="form.html">
    <img src="http://placehold.it/200x100" alt="E-Mail Form" width="256px" height="100px"/>
  </a>
</nav> 

或您可以使用@Alex Char答案或使用此替代解决方案。

#one img:nth-child(2) 
{
    display: none
}

#one:hover img:nth-child(1) 
{
    display: none
}
#one:hover img:nth-child(2) 
{
    display: block
}
<nav>
  <p/><p/>
  <a id="one" href="form.html">
    <img src="http://placehold.it/200x100" alt="E-Mail Form" width="256px" height="100px" />
    <img src="http://placehold.it/400x200" alt="E-Mail Form" width="256px" height="100px"/>
  </a>
</nav> 

答案 3 :(得分:0)

你遇到的问题是,背景图像被分配给一个标签,但是有一个图像覆盖它。

我试试这个:

#one {
    display: inline-block; /* keep it as inline nide but make it aware of width and height */
    width: 256px;
    height: 100px;
    background-image: url('nav.email.gif');
    background-repeat: no-repeat;
    text-indent: -9999px; /* to hide the SEO text */
}

#one:hover {
    background-image: url('nav.email.ani.gif')
}

重要提示:如果您愿意,请删除img标记,并在标记中添加一些SEO文字原因:

<a href="form.html" id="one">Some text for SEO reasons like Contact-Formular foo bar baz</a>

* SEO文字是可选的。

答案 4 :(得分:0)

选项1:使用Css&#39; Hover&#39;

为什么不使用正常的&#39;而不是使用img标签。 div元素?这样,您可以执行类似下面的代码段,它可以设置正常&#39;正常情况下的背景。并且&#39;徘徊&#39; css本身内的版本?

&#13;
&#13;
div {
  height: 200px;
  width: 200px;
  background: url(http://placekitten.com/g/200/200);
}
div:hover {
  background: url(http://placekitten.com/g/200/500);
}
&#13;
<div></div>
&#13;
&#13;
&#13;

选项2:使用Javascript / JQuery替换

此时您可以使用javascript来替换图像的src,但我(个人)认为这比使用css更慢/效率更低,但是,它会遵循:< / p>

$("#myImageID").hover(function(){
    $(this)...
});
相关问题