简体   繁体   中英

How to achieve image changing on hover?

So I am trying to achieve the effect as such on this website .

( Near the bottom where you can hover over the image and it shows another as you move over it )

Any ideas? I mean I know they are just overlaying the two images, but how they then display the far image using CSS/Javascript on hover? This is beyond me. I have tried reproducing it myself with no success.

Try this:

 var main = document.querySelector('.main'); var one = document.querySelector('.one'); var two = document.querySelector('.two'); main.onmousemove = function (e) { var width = e.pageX - e.currentTarget.offsetLeft; one.style.width = width + "px"; two.style.left = width + "px"; } 
 .main { width: 200px; height: 200px; overflow: hidden; position: relative; } .one { background-image: url('http://www.lorempixel.com/200/200'); width: 50%; height: 100%; } .two { background-image: url('http://www.lorempixel.com/200/200/sports'); position: absolute; left: 50%; right: 0px; top: 0px; bottom: 0px; background-position: right; } 
 <div class="main"> <div class="one"></div> <div class="two"></div> </div> 

Working Fiddle

So what's happening is, as the mouse hovers over the line, the width changes dynamically, if you inspect the element, you can see this as well.

Now, in the DOM structure, the brown car, the one being hidden is before the top image. So to achieve this, you can position the brown car absolutely, so it goes right behind the next image, and with javascript or jQuery add a listener for hover, on the image or that middle line that is used on the site, that will change the width of the top image (the silver one) in respect to the position of the mouse in the block of the image.

Essentially, the width of the background image should change by percentage to how far the mouse is from the left of the DIV, by percent ie if the mouse is at the middle, the width should be 50%.

Here is the js they use to do it, right from their site (I uncompressed it)

var ImageSlider = ImageSlider || {};
ImageSlider.Public = function(t) {
"use strict";
var e = t(".image-compare-tool"),
    i = t(".image-compare-images"),
    o = t(".image-compare-top img"),
    a = (t(".image-compare-bottom img"), function(e) {
        e.preventDefault();
        var i, o = t(this).find(".image-compare-top"),
            a = t(this).find(".image-compare-bottom img")[0],
            n = a.getBoundingClientRect();
        i = "mousemove" == e.originalEvent.type ? (e.pageX - n.left) / a.offsetWidth * 100 : (e.originalEvent.touches[0].pageX - n.left) / a.offsetWidth * 100, 100 >= i && o.css({
            width: i + "%"
        })
    }),
    n = function() {
        i.each(function() {
            t(this).on("mousemove", a), t(this).on("touchstart", a), t(this).on("touchmove", a)
        })
    },
    m = function() {
        o.each(function() {
            var e = t(this).attr("src"),
                i = t(this).parent();
            i.css("background-image", "url(" + e + ")")
        })
    },
    c = function() {
        n(), m()
    },
    r = function() {
        e.length > 0 && c()
    };
r()}(jQuery);

If you look at html sources (Ctr + Shift + I in Chrome) you can see this element

<div class="image-compare-tool ICT-theverge">
  <div class="image-compare-images">
    <div class="image-compare-bottom"><img src="http://cdn2.vox-cdn.com/uploads/chorus_asset/file/2455624/khyzyl-saleem-plain-copylow.0.jpg"></div>
    <div class="image-compare-top" style="width: 6.158357771261%; background-image: url(http://cdn0.vox-cdn.com/uploads/chorus_asset/file/2455620/khyzyl-saleem-plain-copylow1.0.jpeg);"><img src="http://cdn0.vox-cdn.com/uploads/chorus_asset/file/2455620/khyzyl-saleem-plain-copylow1.0.jpeg"></div>
  </div>
</div>

So here are images! So next you need to look at css.

.image-compare-tool
{
    max-width:100%;
    width:100%;
    z-index:999;
    margin:0 auto 1.5em 0;
}

.image-compare-images
{
    font-size:0;
    position:relative;
    height:100%;
    -ms-touch-action:none;
    -webkit-touch-callout:none;
    -webkit-user-select:none;
}

.image-compare-images:hover
{
    cursor:col-resize;
}

.image-compare-images img
{
    display:block;
    height:auto;
    width:100%;
}

.image-compare-top,.image-compare-bottom
{
    z-index:0;
    height:100%;
}

.image-compare-top
{
    background-size:cover;
    height:100%;
    left:0;
    position:absolute;
    top:0;
    width:50%;
}

.image-compare-top:after
{
    background-color:#fff;
    content:'';
    height:50px;
    left:calc(100%-5px);
    top:calc(50%-25px);
    position:absolute;
    width:10px;
}

.image-compare-top img
{
    display:none;
}

.ICT-SBNation .image-compare-top:after
{
    background-color:#c52126;
}

.ICT-SBNation .image-compare-top:before
{
    background-color:#c52126;
    content:'';
    height:100%;
    left:calc(100%-2.5px);
    top:0;
    position:absolute;
    width:5px;
}

.ICT-TheVerge .image-compare-top:after
{
    background-color:#fa4b2a;
}

.ICT-TheVerge .image-compare-top:before
{
    background-color:#fa4b2a;
    content:'';
    height:100%;
    left:calc(100%-2.5px);
    top:0;
    position:absolute;
    width:5px;
}

.ICT-Polygon .image-compare-top:after
{
    background-color:#ff0052;
}

.ICT-Polygon .image-compare-top:before
{
    background-color:#ff0052;
    content:'';
    height:100%;
    left:calc(100%-2.5px);
    top:0;
    position:absolute;
    width:5px;
}

.image-compare-top:before,.ICT-Vox .image-compare-top:before
{
    background-color:#fff;
    content:'';
    height:100%;
    left:calc(100%-2.5px);
    top:0;
    position:absolute;
    width:5px;
}

Here wea! You can implement same stuff by just including css and making same html structure and classes with just changing img paths...

And finally the js that i brazenly stole from the answer above:

var ImageSlider = ImageSlider || {};
ImageSlider.Public = function (t) {
    "use strict";
    var e = t(".image-compare-tool"),
        i = t(".image-compare-images"),
        o = t(".image-compare-top img"),
        a = (t(".image-compare-bottom img"), function (e) {
            e.preventDefault();
            var i, o = t(this).find(".image-compare-top"),
                a = t(this).find(".image-compare-bottom img")[0],
                n = a.getBoundingClientRect();
            i = "mousemove" == e.originalEvent.type ? (e.pageX - n.left) / a.offsetWidth * 100 : (e.originalEvent.touches[0].pageX - n.left) / a.offsetWidth * 100, 100 >= i && o.css({
                width: i + "%"
            })
        }),
        n = function () {
            i.each(function () {
                t(this).on("mousemove", a), t(this).on("touchstart", a), t(this).on("touchmove", a)
            })
        },
        m = function () {
            o.each(function () {
                var e = t(this).attr("src"),
                    i = t(this).parent();
                i.css("background-image", "url(" + e + ")")
            })
        },
        c = function () {
            n(), m()
        },
        r = function () {
            e.length > 0 && c()
        };
    r()
}(jQuery);

And the working JSFiddle: http://jsfiddle.net/9gf59k00/
And my good luck...

$('img').on('mousemove', function(){
   var imgsrc = $(this).attr('src');
   if(imgsrc == 'img1.png'){
      $(this).attr('src','img2.png');
   }else{
      $(this).attr('src','img1.png');
   }
});

You can do this without javascript, JSfiddle - http://jsfiddle.net/k4915wwm/

Just…

div:hover {
   background:url("newImage.jpg");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM