【问题标题】:Move the background image on mouse over (Single Parallax)在鼠标上移动背景图像(单视​​差)
【发布时间】:2014-02-26 18:04:12
【问题描述】:

当鼠标在“landing-content”DIV时,我想让背景图像在X和Y轴上稍微移动,它应该随着鼠标的移动而移动。 它应该反向移动。例如。鼠标向下移动,“着陆内容”图像向上移动。

HTML

<div id="landing-content">
<section class="slider"> 
<img src="http://i.imgur.com/fVWomWz.png"></img>
</section>
</div>

CSS

#landing-content {
overflow: hidden;
background-image: url(http://i.imgur.com/F2FPRMd.jpg);
width: 100%;
background-size: cover;
background-repeat: no-repeat;
max-height: 500px;
border-bottom: solid;
border-bottom-color: #628027;
border-bottom-width: 5px;
}

.slider {
margin-left: auto;
margin-right: auto;
overflow: hidden;
padding-top: 200px;
max-width: 1002px;
}

.slider img {
width: 80%;
padding-left: 10%;
padding-right: 10%;
height: auto;
margin-left: auto;
margin-right: auto;
}

JSFiddle http://jsfiddle.net/uMk7m/

我们将不胜感激。

【问题讨论】:

    标签: jquery html css parallax


    【解决方案1】:

    您可以使用 mousemove 事件,如此小提琴所示。 http://jsfiddle.net/X7UwG/

    $('#landing-content').mousemove(function(e){
        var amountMovedX = (e.pageX * -1 / 6);
        var amountMovedY = (e.pageY * -1 / 6);
        $(this).css('background-position', amountMovedX + 'px ' + amountMovedY + 'px');
    });
    

    不过,这只是一个简单的示例,您必须自己处理这些数字。 ;)

    【讨论】:

    • 谢谢,但图像不再“覆盖”div。有什么办法解决这个问题?
    • 对于可移动的背景图像,您需要说它比我认为的 div 大 20-30%。
    • 可以这样做吗和“背景尺寸:封面;”还要申请吗?
    • 我不明白为什么不这样做,但我肯定会在一些不同的浏览器中测试它以确保。
    • 知道你会怎么做吗?
    【解决方案2】:

    你可以这样实现

    $(document).ready(function(){
      $('#landing-content').mousemove(function(e){
        var x = -(e.pageX + this.offsetLeft) / 20;
        var y = -(e.pageY + this.offsetTop) / 20;
        $(this).css('background-position', x + 'px ' + y + 'px');
      });    
    });
    

    http://jsfiddle.net/uMk7m/2/

    【讨论】:

    • 谢谢,但图像不再“覆盖”div。有什么办法解决这个问题?
    • @Simon 使 div 更小,或使用更大的图像。您正在使用使图像适合容器的属性background-size: cover;,您可以像这样删除jsfiddle.net/uMk7m/3,但这取决于您所追求的。
    • 这是更新小提琴jsfiddle.net/X7UwG/2 - 有什么办法可以让图像在 x 和 y 轴的中间居中?
    • @Simon 我不这么认为。您可以拥有原始的 css 状态background-position:center;,然后我认为您必须在 mousemove 期间手动添加中心偏移量,就像这样jsfiddle.net/X7UwG/3
    【解决方案3】:

    检查这个小提琴。我想你会找到你想要的。 http://jsfiddle.net/Aveendra/uXPkE/

    $('#landing-content').mousemove(function(e){
        $(this).css('background-position',''+e.pageX/10+'px '+e.pageY/10+'px');
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多