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

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

问题描述

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

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

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

更新

此后我尝试了@Capt Otis 建议的变体,但我仍然在为我正在使用的代码而苦苦挣扎,如下所示:

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

谁能解释一下我做错了什么?

解决方案

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

CSS

html, body{高度:100%;最小高度:100%;保证金:0;填充:0;}.bg{宽度:100%;高度:100%;背景:#fff url(..) 无重复固定 0 0;溢出:自动;}<div class="bg"><span>..</span>

JavaScript

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

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

<小时>

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.

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.

UPDATE

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?

解决方案

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

Check working example at http://jsfiddle.net/Vbtts/
Click this link for the full screen example: http://jsfiddle.net/Vbtts/embedded/result/


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

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