jQuery在窗口滚动动画背景图像位置 [英] jQuery on window scroll animate background image position

查看:27
本文介绍了jQuery在窗口滚动动画背景图像位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jQuery 实现滚动效果.我将背景 div 设置为 100% 浏览器窗口大小,并隐藏溢出.这有一个大的背景图像,大约是.1500 像素 x 2000 像素.

I am trying to achieve a scrolling effect using jQuery. I have a background div set to 100% browser window size with overflow hidden. This has a large background image that is approx. 1500px x 2000px.

我想要的效果是当用户向下滚动页面时,背景图像会以滚动距离的百分比移动,因此页面每向下滚动 200 像素,图像就会向同一方向移动 10 像素.

The effect I want is when the user scrolls down the page the background image moves at a percentage of the scrolled distance, so for every 200px scrolled down the page the image moves 10px in the same direction.

谁能指出我正确的方向?这甚至可能吗?:) 非常感谢.

Can anyone point me in the right direction? Is this even possible? : ) Many thanks in advance.

更新

我已经尝试了@Capt Otis 建议的变体,但我仍在苦苦挣扎,我正在使用的代码如下:

I have since tried variations on the suggestion by @Capt Otis but I'm still struggling the code I am playing around with is as follows:

$(window).scroll(function(){
    if($(this).scrollTop() > 200) {
        $('#div').animate({'background-postion': '+=10px 0'}, 500);
    }
});     

谁能解释我做错了什么?

Can anyone shed any light on what I am doing wrong?

推荐答案

给你.背景设置为 10% 滚动.您可以通过更改代码中的 10 来更改背景滚动速率.

Here you go. Background is set to 10% scroll. You can change the background scroll rate by changing the 10 in the code.

CSS

html, body{
    height:100%;
    min-height:100%;
    margin:0;
    padding:0;
}
.bg{
    width:100%;
    height:100%;
    background: #fff url(..) no-repeat fixed 0 0;
    overflow:auto;
}

<div class="bg">
   <span>..</span>
</div>

JavaScript

$('.bg').scroll(function() {
    var x = $(this).scrollTop();
    $(this).css('background-position', '0% ' + parseInt(-x / 10) + 'px');
});

http://jsfiddle.net/Vbtts/
查看工作示例单击此链接查看全屏示例:http://jsfiddle.net/Vbtts/embedded/result/

这篇关于jQuery在窗口滚动动画背景图像位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆