使用CSS/HTML在鼠标悬停时改变图像

时间:2022-11-05 14:53:45

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;
}

20 个解决方案

#1


71  

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 over 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;
}

#2


79  

Another option is to use JS:

另一个选择是使用JS:

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

#3


46  

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。“托管”元素是一个带有id“tuxie”的span。

  1. I create 50 x 25 image with two Tuxes, one in color and other gray,
  2. 我创建了50x25的图像,有两个Tuxes,一个是彩色的,另一个是灰色的,
  3. then assign the image as a background for a 25 x 25 span,
  4. 然后将该图像作为25×25跨度的背景,
  5. and finally set the hover to simply move the background 25px left.
  6. 最后,将鼠标悬停设置为只移动背景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:

和图片:

使用CSS/HTML在鼠标悬停时改变图像

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.

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

    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.

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

Note that this is built with background CSS property, so if you really need to use with <img />s, you must not set the src property 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.).

注意,这是使用背景CSS属性构建的,所以如果您确实需要使用使用CSS/HTML在鼠标悬停时改变图像s,则不能设置src属性,因为它与背景重叠。(我开始认为,巧妙地利用透明度可能会产生有趣的结果,但可能非常依赖于图像的质量和引擎。)

#4


29  

Use 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

#5


4  

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.

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

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.

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

#6


4  

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实现的;(它为你提供了一种非常有效的将悬停效果放在一个使用CSS/HTML在鼠标悬停时改变图像上的可能性。)

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");
});

#7


3  

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");
    }
);

#8


2  

.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:

为了改进拉希德的好答案,我加了一些评论:

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.

    如果需要更改这两个图像的url,那么将它们放在同一个位置将会有所帮助。

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

    似乎也适用于老航海家(CSS2标准)。

  • It's self explanatory.

    这是自说明的。

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

    悬停图像被预先加载(悬停后没有延迟)。

#9


1  

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

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

#10


1  

check this fiddle

检查这个小提琴

I think the image path may be wrong in your case

我认为在你的情况下,图像路径可能是错误的。

the syntax looks right

语法是正确的

background-image:url('http://www.bluecowcreative.ca/wp-content/uploads/2013/08/hi.jpg');

#11


1  

try one of them

试着其中的一个

<img src='images/icons/proceed_button.png' width='120' height='70' onmouseover="this.src='images/icons/proceed_button2.png';" onmouseout="this.src='images/icons/proceed_button.png';" />

or if you using image as a button in form

或者如果你使用图像作为一个按钮的形式。

<input type="image" id="proceed" src="images/icons/proceed_button.png" alt"Go to Facebook page" onMouseOver="fnover();"onMouseOut="fnout();" onclick="fnclick()">
function fnover()
        {
            var myimg2 = document.getElementById("proceed");
            myimg2.src = "images/icons/proceed_button2.png";
        }

        function fnout()
        {
            var myimg2 = document.getElementById("proceed");
            myimg2.src = "images/icons/proceed_button.png";
        }

#12


1  

.foo img:last-child{display:none}
.foo:hover img:first-child{display:none}
.foo:hover img:last-child{display:inline-block}
<body> 
    <a class="foo" href="#">
        <img src="http://lojanak.com/image/9/280/280/1/0" />
        <img src="http://lojanak.com/image/0/280/280/1/0" />
    </a>
</body>

#13


0  

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');
}

#14


0  

In the way that you're doing things, it won't happen. You're changing the background image of the image, which is being blocked by the original image. Changing the height and width also won't happen. To change the src attribute of the image, you would need Javascript or a Javascript Library such as jQuery. You could however, change the image to a simple div (text) box, and have a background image that changes on hover, even though the div box itself will be empty. Here's how.

在你做事的过程中,它不会发生。您正在更改图像的背景图像,该图像正被原始图像阻塞。改变高度和宽度也不会发生。要更改图像的src属性,需要Javascript或jQuery等Javascript库。但是,您可以将图像更改为一个简单的div(文本)框,并拥有一个对悬停进行更改的背景图像,即使div框本身将是空的。这是如何。

<div id="emptydiv"></div>

#emptydiv {

background-image: url("LibraryHover.png");
height: 70px;
width: 120px;

}

}

#emptydiv:hover {

background-image: url("LibraryHoverTrans.png");
height: 700px;
width: 1200px;

}

I hope this is what you're asking for :)

我希望这就是你想要的

#15


0  

With everyones answer using the background-image option they're missing one attribute. The height and width will set the container size for the image but won't resize the image itself. background-size is needed to compress or stretch the image to fit this container. I've used the example from the 'best answer'

对于使用背景图像选项的每个人的答案,他们都丢失了一个属性。高度和宽度将设置图像的容器大小,但不会调整图像本身的大小。需要使用背景大小来压缩或拉伸图像以适应这个容器。我用了“最佳答案”中的例子

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

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

#16


0  

Just use Photoshop and create two of the same image, the 1st one being how you want it to look, the 2nd being how you want it to look when it's hovered over. I'm wrapping the image in an <a> tag, because I'm assuming that it's what you want. For this example I'm doing a facebook icon which is desaturated, but when hovered over it will show the blue color of facebook.

只需使用Photoshop,创建两个相同的图像,第一个是你想让它看起来的样子,第二个是你想让它在盘旋时看起来的样子。我将图像包装在标签中,因为我假设它是你想要的。在这个例子中,我使用的是一个facebook图标,它被取消了,但是当它在上面停留的时候,会显示出facebook的蓝色。

<a href="www.facebook.com"><img src="place of 1st image" onmouseover="this.src='place of 2nd image'" onmouseout="this.src='place of 1st image'"></a>

#17


0  

My jquery solution.

我的jquery的解决方案。

function changeOverImage(element) {
        var url = $(element).prop('src'),
            url_over = $(element).data('change-over')
        ;

        $(element)
            .prop('src', url_over)
            .data('change-over', url)
        ;
    }
    $(document).delegate('img[data-change-over]', 'mouseover', function () {
        changeOverImage(this);
    });
    $(document).delegate('img[data-change-over]', 'mouseout', function () {
        changeOverImage(this);
    });

and html

和html

<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=%3Cimg%20original%20/%3E&w=342&h=300" data-change-over="https://placeholdit.imgix.net/~text?txtsize=33&txt=%3Cimg%20over%20/%3E&w=342&h=300" />

Demo: JSFiddle demo

演示:JSFiddle演示

Regards

问候

#18


0  

Live Example: JSFiddle

生活例子:JSFiddle

The Accepted answer has some problem. The image wasn't resized there. Use background-size property for resizing the image.

公认的答案有一些问题。图像没有调整大小。使用背景大小属性来调整图像的大小。

HTML:

HTML:

<div id="image"></div>

CSS:

CSS:

#image {
   background-image: url('image1');
   background-size: 300px 390px;
   width: 300px;
   height:390px;
}

#image:hover{
  background: url("image2");
  background-size: 300px 390px;
}

#19


0  

Here is the simple trick. Just copy and paste it.

这里有一个简单的技巧。复制粘贴。

<!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Change Image on Hover in CSS</title>
    <style type="text/css">
        .card {
            width: 130px;
            height: 195px;
            background: url("../images/card-back.jpg") no-repeat;
            margin: 50px;
        }
        .card:hover {
            background: url("../images/card-front.jpg") no-repeat;
        }
    </style>
    </head>
    <body>
        <div class="card"></div>
    </body>
    </html>       

#20


0  

What I would recommend is to use only CSS if possible. My solution would be:

我的建议是,如果可能的话,只使用CSS。我的解决方案是:

HTML:

HTML:

<img id="img" class="" src="" />

CSS:

CSS:

img#img{
    background: url("pictureNumberOne.png");
    background-size: 100px 100px;
    /* Optional transition: */
    transition: background 0.25s ease-in-out;
}
img#img:hover{
    background: url("pictureNumberTwo.png");
    background-size: 100px 100px;
}

That (not defining the src attribute) also ensures that transparent images (or images with transparent parts) are shown correctly (otherwise, if the second pic would be half-transparent, you would also see parts of the first picture).

这(不定义src属性)也可以确保透明的图像(或者透明部分的图像)被正确显示(否则,如果第二张图片是半透明的,你也会看到第一张图片的部分)。

The background-size attribute is used to set the height and width of a background-image.

背景大小属性用于设置背景图像的高度和宽度。

If (for any reason) you don't want to change the bg-image of an image, you could also put the image in a div-container as following:

如果(由于任何原因)您不希望更改图像的bg-image,您还可以将图像放在div-container中,如下所示:

HTML:

HTML:

<div id="imgContainer" class="">
    <img id="" class="" src="" />
</div>

... and so on.

…等等。

#1


71  

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 over 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;
}

#2


79  

Another option is to use JS:

另一个选择是使用JS:

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

#3


46  

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。“托管”元素是一个带有id“tuxie”的span。

  1. I create 50 x 25 image with two Tuxes, one in color and other gray,
  2. 我创建了50x25的图像,有两个Tuxes,一个是彩色的,另一个是灰色的,
  3. then assign the image as a background for a 25 x 25 span,
  4. 然后将该图像作为25×25跨度的背景,
  5. and finally set the hover to simply move the background 25px left.
  6. 最后,将鼠标悬停设置为只移动背景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:

和图片:

使用CSS/HTML在鼠标悬停时改变图像

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.

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

    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.

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

Note that this is built with background CSS property, so if you really need to use with <img />s, you must not set the src property 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.).

注意,这是使用背景CSS属性构建的,所以如果您确实需要使用使用CSS/HTML在鼠标悬停时改变图像s,则不能设置src属性,因为它与背景重叠。(我开始认为,巧妙地利用透明度可能会产生有趣的结果,但可能非常依赖于图像的质量和引擎。)

#4


29  

Use 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

#5


4  

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.

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

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.

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

#6


4  

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实现的;(它为你提供了一种非常有效的将悬停效果放在一个使用CSS/HTML在鼠标悬停时改变图像上的可能性。)

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");
});

#7


3  

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");
    }
);

#8


2  

.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:

为了改进拉希德的好答案,我加了一些评论:

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.

    如果需要更改这两个图像的url,那么将它们放在同一个位置将会有所帮助。

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

    似乎也适用于老航海家(CSS2标准)。

  • It's self explanatory.

    这是自说明的。

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

    悬停图像被预先加载(悬停后没有延迟)。

#9


1  

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

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

#10


1  

check this fiddle

检查这个小提琴

I think the image path may be wrong in your case

我认为在你的情况下,图像路径可能是错误的。

the syntax looks right

语法是正确的

background-image:url('http://www.bluecowcreative.ca/wp-content/uploads/2013/08/hi.jpg');

#11


1  

try one of them

试着其中的一个

<img src='images/icons/proceed_button.png' width='120' height='70' onmouseover="this.src='images/icons/proceed_button2.png';" onmouseout="this.src='images/icons/proceed_button.png';" />

or if you using image as a button in form

或者如果你使用图像作为一个按钮的形式。

<input type="image" id="proceed" src="images/icons/proceed_button.png" alt"Go to Facebook page" onMouseOver="fnover();"onMouseOut="fnout();" onclick="fnclick()">
function fnover()
        {
            var myimg2 = document.getElementById("proceed");
            myimg2.src = "images/icons/proceed_button2.png";
        }

        function fnout()
        {
            var myimg2 = document.getElementById("proceed");
            myimg2.src = "images/icons/proceed_button.png";
        }

#12


1  

.foo img:last-child{display:none}
.foo:hover img:first-child{display:none}
.foo:hover img:last-child{display:inline-block}
<body> 
    <a class="foo" href="#">
        <img src="http://lojanak.com/image/9/280/280/1/0" />
        <img src="http://lojanak.com/image/0/280/280/1/0" />
    </a>
</body>

#13


0  

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');
}

#14


0  

In the way that you're doing things, it won't happen. You're changing the background image of the image, which is being blocked by the original image. Changing the height and width also won't happen. To change the src attribute of the image, you would need Javascript or a Javascript Library such as jQuery. You could however, change the image to a simple div (text) box, and have a background image that changes on hover, even though the div box itself will be empty. Here's how.

在你做事的过程中,它不会发生。您正在更改图像的背景图像,该图像正被原始图像阻塞。改变高度和宽度也不会发生。要更改图像的src属性,需要Javascript或jQuery等Javascript库。但是,您可以将图像更改为一个简单的div(文本)框,并拥有一个对悬停进行更改的背景图像,即使div框本身将是空的。这是如何。

<div id="emptydiv"></div>

#emptydiv {

background-image: url("LibraryHover.png");
height: 70px;
width: 120px;

}

}

#emptydiv:hover {

background-image: url("LibraryHoverTrans.png");
height: 700px;
width: 1200px;

}

I hope this is what you're asking for :)

我希望这就是你想要的

#15


0  

With everyones answer using the background-image option they're missing one attribute. The height and width will set the container size for the image but won't resize the image itself. background-size is needed to compress or stretch the image to fit this container. I've used the example from the 'best answer'

对于使用背景图像选项的每个人的答案,他们都丢失了一个属性。高度和宽度将设置图像的容器大小,但不会调整图像本身的大小。需要使用背景大小来压缩或拉伸图像以适应这个容器。我用了“最佳答案”中的例子

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

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

#16


0  

Just use Photoshop and create two of the same image, the 1st one being how you want it to look, the 2nd being how you want it to look when it's hovered over. I'm wrapping the image in an <a> tag, because I'm assuming that it's what you want. For this example I'm doing a facebook icon which is desaturated, but when hovered over it will show the blue color of facebook.

只需使用Photoshop,创建两个相同的图像,第一个是你想让它看起来的样子,第二个是你想让它在盘旋时看起来的样子。我将图像包装在标签中,因为我假设它是你想要的。在这个例子中,我使用的是一个facebook图标,它被取消了,但是当它在上面停留的时候,会显示出facebook的蓝色。

<a href="www.facebook.com"><img src="place of 1st image" onmouseover="this.src='place of 2nd image'" onmouseout="this.src='place of 1st image'"></a>

#17


0  

My jquery solution.

我的jquery的解决方案。

function changeOverImage(element) {
        var url = $(element).prop('src'),
            url_over = $(element).data('change-over')
        ;

        $(element)
            .prop('src', url_over)
            .data('change-over', url)
        ;
    }
    $(document).delegate('img[data-change-over]', 'mouseover', function () {
        changeOverImage(this);
    });
    $(document).delegate('img[data-change-over]', 'mouseout', function () {
        changeOverImage(this);
    });

and html

和html

<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=%3Cimg%20original%20/%3E&w=342&h=300" data-change-over="https://placeholdit.imgix.net/~text?txtsize=33&txt=%3Cimg%20over%20/%3E&w=342&h=300" />

Demo: JSFiddle demo

演示:JSFiddle演示

Regards

问候

#18


0  

Live Example: JSFiddle

生活例子:JSFiddle

The Accepted answer has some problem. The image wasn't resized there. Use background-size property for resizing the image.

公认的答案有一些问题。图像没有调整大小。使用背景大小属性来调整图像的大小。

HTML:

HTML:

<div id="image"></div>

CSS:

CSS:

#image {
   background-image: url('image1');
   background-size: 300px 390px;
   width: 300px;
   height:390px;
}

#image:hover{
  background: url("image2");
  background-size: 300px 390px;
}

#19


0  

Here is the simple trick. Just copy and paste it.

这里有一个简单的技巧。复制粘贴。

<!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Change Image on Hover in CSS</title>
    <style type="text/css">
        .card {
            width: 130px;
            height: 195px;
            background: url("../images/card-back.jpg") no-repeat;
            margin: 50px;
        }
        .card:hover {
            background: url("../images/card-front.jpg") no-repeat;
        }
    </style>
    </head>
    <body>
        <div class="card"></div>
    </body>
    </html>       

#20


0  

What I would recommend is to use only CSS if possible. My solution would be:

我的建议是,如果可能的话,只使用CSS。我的解决方案是:

HTML:

HTML:

<img id="img" class="" src="" />

CSS:

CSS:

img#img{
    background: url("pictureNumberOne.png");
    background-size: 100px 100px;
    /* Optional transition: */
    transition: background 0.25s ease-in-out;
}
img#img:hover{
    background: url("pictureNumberTwo.png");
    background-size: 100px 100px;
}

That (not defining the src attribute) also ensures that transparent images (or images with transparent parts) are shown correctly (otherwise, if the second pic would be half-transparent, you would also see parts of the first picture).

这(不定义src属性)也可以确保透明的图像(或者透明部分的图像)被正确显示(否则,如果第二张图片是半透明的,你也会看到第一张图片的部分)。

The background-size attribute is used to set the height and width of a background-image.

背景大小属性用于设置背景图像的高度和宽度。

If (for any reason) you don't want to change the bg-image of an image, you could also put the image in a div-container as following:

如果(由于任何原因)您不希望更改图像的bg-image,您还可以将图像放在div-container中,如下所示:

HTML:

HTML:

<div id="imgContainer" class="">
    <img id="" class="" src="" />
</div>

... and so on.

…等等。