使用Scrolling Parallax jQuery插件时保持图像宽高比完好无损

时间:2012-06-21 18:52:25

标签: jquery css scroll parallax

我正在使用Scrolling Parallax jQuery plugin滚动"背景" this site上的图片(实际上不是css背景图片)。

是否可以保持图像宽高比,即不压缩图像,仍然可以在所有现代浏览器中使用?

我尝试设置bgHeight : 'auto',将图片css设置为height:auto,但这会停止Chrome和Safari中的滚动效果。

我也尝试设置bgWidth : 'auto'但是图像比浏览器窗口窄。

也可以使用其他插件或实现此效果的方式,即让背景图像以不同的速率滚动到页面内容,同时显示整个图像,但不滚动过去...

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

由于宽度自动设置为视口的100%,因此除非您更改,否则将进行拉伸。

使用此:

$.scrollingParallax('img/clouds.png', {
    bgHeight : '250%',
    staticSpeed : .25,
    staticScrollLimit : false,
    bgWidth: 'auto'
});

以上内容可见:jsFiddle


由于未拉伸的背景图像总是向左浮动,我掀起了一些jQuery的优点,因此图像始终在视口中居中,即使在 Window Resize Event 期间也是如此。也就是说,图像现在可以扩展到最大图像大小或缩小,同时在所有浏览器中保留纵横比。

$(function() {

    // Specify your background image here.
    var bgMain = 'http://indigobrazilianportuguese.com/2012/wp-content/uploads/Home_bg1600.jpg';

    $.scrollingParallax(bgMain, {
        bgHeight : '200%',
        staticSpeed : 0.25,
        staticScrollLimit : false,
        // Important to set to 'auto' so Aspect Ratio for width is preserved because height defined above is fixed.
        bgWidth: 'auto'
    });

    // These two lines is for page load.
    // The variable will calculate CSS 'left' for the background image to center it in the viewport.
    // First, horizontal viewport size is checked via $(window).width()
    // Then, image width is determined by searching for image's unique filepath/filename.
    // Once the different is known, this value is then divided by 2 so that equal space is seen on left and right side of image which becomes the variable value.
    var bgMainHcenter = ( $(window).width() - $('body img[src="' + bgMain + '"]').width() ) /2 ;
    $('body img[src="' + bgMain + '"]').css('left', bgMainHcenter + 'px');

    // Just like above, it's repeated during Window Resize Event.
    $(window).resize(function() {
        bgMainHcenter = ( $(window).width() - $('body img[src="' + bgMain + '"]').width() ) /2 ;
        $('body img[src="' + bgMain + '"]').css('left', bgMainHcenter + 'px');
    });

});

在此处查看此操作: jsFiddle

答案 1 :(得分:0)

好的,所以根据他们的主页你可以设置%的宽度和高度,所以我会先尝试一下,看看它是怎么回事。