2014-02-26 19 views
1

我拼命寻找我的客户的解决方案。我有图形 - 这样的事情:如何在用户控制重叠图像在JS

slider

而且我希望能够采取符合圆圈的中心并将其拖动到右边或左边。它将隐藏和取消隐藏我的两幅完整图像。这基本上是两个图像在同一个地方,只是与另一个Z-索引,我认为。

我认为可以用JavaScript来做,但我不知道这个选项的功能或方法。

+0

可能与一个jQuery滑块做,但不知道到底什么工作。 – RacerNerd

回答

2

这里是我的解决方案:

的HTML是相当简单,只需两个div的图像和一个用于拖拽:

<div class="img" id="img1"></div> 
<div class="img" id="img2"></div> 
<div id="drag"></div> 

对于CSS的重要组成部分,是绝对位置的所有divs并给出背景图片。

对于JavaScript中,与jQuery的一点帮助,我们侦听鼠标事件,使一些计算和调整第二图像的CSS:

$('#drag').on('mousedown', function(e){ 
    var $self = $(this), 
     dragPos = $self.position().left + $self.width()/2, 
     imgWidth = $('#img1').width(); 

    $(document).on('mouseup', function(e){ 
     $(document).off('mouseup').off('mousemove'); 
    }); 

    $(document).on('mousemove', function(me){ 
     var mx = me.pageX - e.pageX + dragPos 
     $self.css({ left: mx }); 

     $('#img2').css({ 
      width: imgWidth - mx, 
      left: mx, 
      backgroundPosition: -mx + 'px 0px', 
     }); 
    }); 
}); 

从那里,我认为这是很容易定制它并赋予其独特的外观。 希望这有助于!

JsFiddle Demo

+0

因此,您基本上将左侧图像div的宽度设置为在分隔符处结束,并将右侧图像的背景设置为始终排列在左侧图像的左侧,是吗?工作得很好,工作很好。 – hannebaumsaway

+0

这很好用! –

0

this alphamask plugin这样的东西可能会诀窍,但我不确定它是多么简单,你会以你的滑块例子的方式来实现。

+0

感谢您的回答。但这似乎并不是我要找的。有过滤模糊的东西,我想100%隐藏和取消隐藏。 –

+1

@JohnCz。我了解该页面上的示例并非完全符合您的要求。我说的基本功能是你要做的核心:使用一个图像来掩盖另一个图像,并允许用户控制该掩码。你必须真正投入一些工作来定制一个类似我所链接的库来使它适合你的特定需求。 – hannebaumsaway

0

其实很简单。第一步是使其手动工作。我将它设置如下:

<div class="wrap" id="wrap1"> 
    <div class="img-wrap img1"></div> 
    <div class="img-wrap img2"></div> 
<div> 

使用CSS如下:

.wrap { 
    position: relative; 
    width: 300px; 
    height: 300px; 
} 

.img-wrap { 
    width: 100%; 
    height: 100%; 
    position: absolute; 
    top: 0px; 
    left: 0px; 
} 

.img1 { 
    z-index: 1; 
    background: url(bg1.png) no-repeat 0px 0px; 
} 

.img2 { 
    z-index: 2; 
    background: url(bg1.png) no-repeat 0px 0px; 
} 

现在一些JavaScript(用jQuery)设置的位置(当您通过移动滑块,你可以调用这个后面的顶部):

function setPosition(percentage){ 
    // get the width of the container 
    var w = $('#wrap1').width(); 
    // work out the width of left panel 
    var w1 = Math.floor(w * percentage); 
    // and the right panel 
    var w2 = w - w1; 
    // set the width of the right panel 
    // move it right by the width of the left panel 
    // and move the background back by the width of the left panel 
    $('#wrap1 .img2').css({ 
    width: w2, 
    left: w1, 
    backgroundPosition: -w1 + 'px 0px', 
    }); 
} 

您现在只需决定如何进行拖动。你甚至可以在mouseOver上做到这一点。简单!