使用 CSS/HTML 更改悬停时的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18813299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:26:56  来源:igfitidea点击:

Changing image on hover with CSS/HTML

htmlcssimagehover

提问by user2704743

I have this problem where I have set an image to display another image when the mouse hovers over, however the first image still appears and the new one doesn't change height and width and overlaps the other one. I'm still pretty new to HTML/CSS so I may have missed something simple. Here is the code:

我有这个问题,当鼠标悬停在上面时,我设置了一个图像以显示另一个图像,但是第一个图像仍然出现,而新的图像不会改变高度和宽度并与另一个图像重叠。我对 HTML/CSS 还是很陌生,所以我可能错过了一些简单的东西。这是代码:

<img src="LibraryTransparent.png" id="Library">
#Library {
    height: 70px;
    width: 120px;
}

#Library:hover {
    background-image: url('LibraryHoverTrans.png');
    height: 70px;
    width: 120px;
}

回答by kurdtpage

Another option is to use JS:

另一种选择是使用 JS:

<img src='LibraryTransparent.png' onmouseover="this.src='LibraryHoverTrans.png';" onmouseout="this.src='LibraryTransparent.png';" />

回答by Aurelio De Rosa

One solution is to use also the first image as a background image like this:

一个解决方案是也使用第一张图像作为背景图像,如下所示:

<div id="Library"></div>
#Library {
   background-image: url('LibraryTransparent.png');
   height: 70px;
   width: 120px;
}

#Library:hover {
   background-image: url('LibraryHoverTrans.png');
}

If your hover image has a different size, you've got to set them like so:

如果您的悬停图像具有不同的大小,您必须像这样设置它们:

#Library:hover {
   background-image: url('LibraryHoverTrans.png');
   width: [IMAGE_WIDTH_IN_PIXELS]px;
   height: [IMAGE_HEIGHT_IN_PIXELS]px;
}

回答by Alois Mahdal

What I usually do is that I create a double image with both states, acting like kind of a two-frame film which I then use with as background for the original element so that the element has width / height set in pixels, resulting in showing only one half of the image. Then what the hover state defines is basically "move the film to show the other frame".

我通常做的是创建一个具有两种状态的双重图像,就像一种双帧电影,然后我将其用作原始元素的背景,以便元素以像素为单位设置宽度/高度,从而显示图像只有一半。那么悬停状态定义的基本上是“移动电影以显示另一帧”。

For example, imagine that the image has to be a gray Tux, that we need to change to colorful Tux on hover. And the "hosting" element is a span with id "tuxie".

例如,假设图像必须是灰色的 Tux,我们需要在悬停时更改为彩色的 Tux。而“hosting”元素是一个ID为“tuxie”的span。

  1. I create 50 x 25 image with two Tuxes, one in color and other gray,
  2. then assign the image as a background for a 25 x 25 span,
  3. and finally set the hover to simply move the background 25px left.
  1. 我用两个燕尾服创建了 50 x 25 的图像,一个是彩色的,另一个是灰色的,
  2. 然后将图像指定为 25 x 25 跨度的背景,
  3. 最后将悬停设置为简单地将背景向左移动 25px。

The minimal code:

最小代码:

<style>
    #tuxie {
        width: 25px; height: 25px;
        background: url('images/tuxie.png') no-repeat left top;
    }
    #tuxie:hover { background-position: -25px 0px }
</style>

<div id="tuxie" />

and the image:

和图像:

Two-frame Tuxie "film"

两幅图解“电影”

Advantages are:

优点是:

  • By putting both frames in one file, it's ensured that they are loaded at once. This avoids the ugly glitch on slower connections when the other frame never loads immediately, so first hover never works properly.

  • It may be easier to manage your images this way since "paired" frames are never confused.

  • With smart use of Javascript or CSS selector, one can extend this and include even more frames in one file.

    In theory you could put even multiple buttons in single file and govern their display by coordinates, although such approach could get quickly out of hand.

  • 通过将两个帧放在一个文件中,可以确保同时加载它们。这避免了当另一帧永远不会立即加载时较慢连接上的丑陋故障,因此第一次悬停永远无法正常工作。

  • 以这种方式管理图像可能更容易,因为“配对”帧永远不会混淆。

  • 通过巧妙地使用 Javascript 或 CSS 选择器,您可以扩展它并在一个文件中包含更多帧。

    理论上,您甚至可以将多个按钮放在一个文件中,并通过坐标控制它们的显示,尽管这种方法可能很快就会失控。

Note that this is built with backgroundCSS property, so if you really need to use with <img />s, you must notset the srcproperty since that overlaps the background. (Come to think that clever use of transparency here could lead to interesting results, but probably very dependent on quality of image as well as of the engine.).

请注意,这是使用backgroundCSS 属性构建的,因此如果您确实需要使用 with <img />s,则不得设置该src属性,因为它与背景重叠。(想想这里巧妙地使用透明度可能会产生有趣的结果,但可能非常依赖于图像质量和引擎。)。

回答by Vucko

Use content:

使用content

#Library {
    height: 70px;
    width: 120px;
}

#Library:hover {
    content: url('http://www.furrytalk.com/wp-content/uploads/2010/05/2.jpg');
    height: 70px;
    width: 120px;
}

JSFiddle

JSFiddle

回答by Darío Pm

.hover_image:hover {text-decoration: none} /* Optional (avoid undesired underscore if a is used as wrapper) */
.hide {display:none}
/* Do the shift: */
.hover_image:hover img:first-child{display:none}
.hover_image:hover img:last-child{display:inline-block}
<body> 
    <a class="hover_image" href="#">
        <!-- path/to/first/visible/image: -->
        <img src="http://farmacias.dariopm.com/cc2/_cc3/images/f1_silverstone_2016.jpg" />
        <!-- path/to/hover/visible/image: -->
        <img src="http://farmacias.dariopm.com/cc2/_cc3/images/f1_malasia_2016.jpg" class="hide" />
    </a>
</body>

To try to improve this Rashid's good answer I'm adding some comments:

为了尝试改进这个 Rashid 的好答案,我添加了一些评论:

The trick is done over the wrapper of the image to be swapped (an 'a' tag this time but maybe another) so the 'hover_image' class has been put there.

技巧是在要交换的图像的包装器上完成的(这次是一个 'a' 标签,但可能是另一个),所以 'hover_image' 类已经放在那里了。

Advantages:

好处:

  • Keeping both images url together in the same place helps if they need to be changed.

  • Seems to work with old navigators too (CSS2 standard).

  • It's self explanatory.

  • The hover image is preloaded (no delay after hovering).

  • 如果需要更改,将两个图像 url 放在同一个位置会有所帮助。

  • 似乎也适用于旧导航器(CSS2 标准)。

  • 这是不言自明的。

  • 悬停图像已预加载(悬停后无延迟)。

回答by Y2H

The problem with all the previous answers is that the hover image isn't loaded with the page so when the browser calls it, it takes time to load and the whole thing doesn't look really good.

前面所有答案的问题是悬停图像未随页面加载,因此当浏览器调用它时,加载需要时间,并且整个内容看起来不太好。

What I do is that I put the original image and the hover image in 1 element and hide the hover image at first. Then at hover in I display the hover image and hide the old one, and at hover out I do the opposite.

我所做的是将原始图像和悬停图像放在 1 个元素中并首先隐藏悬停图像。然后在悬停时显示悬停图像并隐藏旧图像,在悬停时我做相反的事情。

HTML:

HTML:

<span id="bellLogo" onmouseover="hvr(this, 'in')" onmouseleave="hvr(this, 'out')">
  <img src="stylesheets/images/bell.png" class=bell col="g">
  <img src="stylesheets/images/bell_hover.png" class=bell style="display:none" col="b">
</span>

JavaScript/jQuery:

JavaScript/jQuery:

function hvr(dom, action)
{
    if (action == 'in')
    {
        $(dom).find("[col=g]").css("display", "none");
        $(dom).find("[col=b]").css("display", "inline-block");
    }

    else
    {
        $(dom).find("[col=b]").css("display", "none");
        $(dom).find("[col=g]").css("display", "inline-block");
    }
}

This to me is the easiest and most efficient way to do it.

这对我来说是最简单、最有效的方法。

回答by Nishanth Shaan

You can replace the image of an HTML IMG without needing to make any background image changes to the container div.

您可以替换 HTML IMG 的图像,而无需对容器 div 进行任何背景图像更改。

This is obtained using the CSS property box-sizing: border-box;(It gives you a possibility to put a kind of hover effect on an <IMG>very efficiently.)

这是使用 CSS 属性获得的box-sizing: border-box;(它使您可以<IMG>非常有效地放置一种悬停效果。)

To do this, apply a class like this to your image:

为此,请将这样的类应用于您的图像:

.image-replacement {
  display: block;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: url(http://akamaicovers.oreilly.com/images/9780596517748/cat.gif) no-repeat;/* this image will be shown over the image iSRC */
  width: 180px;
  height: 236px;
  padding-left: 180px;
}

Sample code: http://codepen.io/chriscoyier/pen/cJEjs

示例代码:http: //codepen.io/chriscoyier/pen/cJEjs

Original article: http://css-tricks.com/replace-the-image-in-an-img-with-css/

原文:http: //css-tricks.com/replace-the-image-in-an-img-with-css/

Hope this will help some of you guys who don't want to put a div to obtain an image having a "hover" effect.

希望这会帮助一些不想放置 div 以获得具有“悬停”效果的图像的人。

Posting here the sample code:

在此处发布示例代码:

HTML:

HTML:

<img id="myImage" src="images/photo1.png" class="ClassBeforeImage-replacement">

jQuery:

jQuery:

$("#myImage").mouseover(function () {
    $(this).attr("class", "image-replacement");
});
$("#myImage").mouseout(function () {
    $(this).attr("class", "ClassBeforeImage-replacement");
});

回答by Asaf

You can't use CSS to change image SRC attributes (unless the browser supports it). You may want to use jQuery with the hover event.

您不能使用 CSS 来更改图像 SRC 属性(除非浏览器支持)。您可能希望将 jQuery 与悬停事件一起使用。

$("#Library ").hover(
    function () {
         $(this).attr("src","isHover.jpg");
    },
    function () {
        $(this).attr("src","notHover.jpg");
    }
);

回答by Jacques ジャック

Change the imgtag to a div and give it a background in CSS.

img标签更改为 div 并在 CSS 中为其提供背景。

回答by Tomzan

The problem is that you set the first image through 'src' attribute and on hover added to the image a background-image. try this:

问题是您通过 'src' 属性设置了第一张图像,并在悬停时将背景图像添加到图像中。尝试这个:

in html use:

在 html 中使用:

<img id="Library">

then in css:

然后在css中:

#Library {
    height: 70px;
    width: 120px;
    background-image: url('LibraryTransparent.png');
}

#Library:hover {
    background-image: url('LibraryHoverTrans.png');
}