如何在鼠标悬停时实现图像更改?

3
我正在尝试实现这个网站上的效果。(在靠近底部的地方,你可以将鼠标悬停在图片上并移动它,会显示另一张图片) 你有什么想法吗?我的意思是我知道他们只是将两张图像叠加在一起,但是他们如何使用CSS/Javascript在悬停时显示远程图像呢?这超出了我的能力范围。我已经尝试过自己复制,但没有成功。

1
从未见过这样的功能..看起来很有趣 :) - Mr_Green
参见:http://demosthenes.info/blog/819/A-Before-And-After-Image-Comparison-Slide-Control-in-HTML5 - Kolban
好问题,所以+1。 - HaveNoDisplayName
5个回答

7

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


1
当鼠标悬停在线上时,宽度会动态改变。如果检查元素,也可以看到这一点。现在,在DOM结构中,被隐藏的褐色汽车位于顶部图像之前。因此,可以将褐色汽车绝对定位,使其直接位于下一张图片后面,并使用javascript或jQuery在图像或网站上使用的中间线上添加悬停侦听器,以便根据鼠标在图像块中的位置更改顶部图像(银色图像)的宽度。本质上,背景图像的宽度应按百分比相对于鼠标距离DIV左侧的距离进行更改,例如,如果鼠标在中间,则宽度应为50%。以下是他们从网站上使用的js代码(我未压缩它)。
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);

1
干得好!如果它有人类可理解的函数名称,那就太棒了!! - Akshay Khandelwal

1

如果你查看HTML源代码(在Chrome中按下Ctrl + Shift + I),你可以看到这个元素。

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

这里有图片!接下来您需要查看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;
}

在这里,您可以通过包含CSS并使用相同的HTML结构和类来实现相同的内容,只需更改img路径即可使内容更加通俗易懂...

最后,我从上面的答案中大胆地窃取了js:

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

以下是工作中的JSFiddle链接:http://jsfiddle.net/9gf59k00/
祝我好运...


这不是答案……这只是将代码从那个网站复制并粘贴到答案中…… - Simply Craig
2
那么答案是什么呢?答案是理论吗?你能提出什么理论?宇宙大爆炸理论?我知道我错了,因为我忘记了 JavaScript。 - RussianVodka
哈哈...太有趣了。+1 只是为了好玩。 - Yang
@SimplyCraig 这是一个尝试回答。 - Compass
我不确定为什么需要这么多的代码?我在下面的答案中用几行JavaScript实现了相同的功能。是因为要支持移动设备吗? - Mr_Green
显示剩余2条评论

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

3
他很可能在谈论底部的汽车图片,该图片具有滑块效果以显示图像的一部分。并不仅仅是在悬停时直接替换图片。 - Simply Craig
1
@SimplyCraig - 如果你不喜欢这个答案,应该给它点踩,而不是举报。举报应该是针对那些根本没有试图回答问题的答案(例如,如果他们留下了评论、链接或另一个问题,而不是作为答案的尝试)。 - ArtOfWarfare
@ArtOfWarfare 我从未标记过这篇帖子,你在说什么? - Simply Craig
@SimplyCraig - 抱歉,最近有人匿名举报了它,由于你最近留下了负面评论,所以我认为是你干的。 - ArtOfWarfare
@ArtOfWarfare 哦,好的,不是我。 - Simply Craig

-1

你可以在没有JavaScript的情况下完成这个任务, JSFiddle - http://jsfiddle.net/k4915wwm/

只需要…

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

1
请仔细阅读问题,并参考提供的链接! - Akshay Khandelwal
我想问题应该被更好地提出。我访问了提供的链接,但它只是在你悬停在上面时改变了图像。 - Dan Goodspeed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接