2014-03-03 277 views
0

我要滾動的背景圖像,直到最後像素,然後倒退到圖像的開始。我想不斷重複這個順序。滾動背景圖像

我有一個代碼,但它在一個方向上連續滾動的背景圖像。

我怎麼能更改此代碼工作,我想要什麼?

CSS:

body{margin:0; border:0; background:url(ejemplo3.jpg) repeat-x;} 

HTML:

<body></body> 

JQuery的:

var scrollSpeed = 50; 

// set the default position 
var current = 0; 

// set the direction 
var direction = 'h'; 

function bgscroll() { 
    // 1 pixel row at a time 
    current -= 1; 

    // move the background with backgrond-position css properties 
    $('body').css("backgroundPosition", (direction == 'h') ? current + "px 0" : "0 " + current + "px"); 
} 

//Calls the scrolling function repeatedly 
setInterval(bgscroll, scrollSpeed); 

回答

0

當你有背景重複-X然後它會進入一個循環,因此你會看到圖像只在一個方向旋轉。

/*添加背景圖片(assing圖像)*/

body{margin:0; border:0; background:url(dsc01549.jpg) no-repeat;} 

/*地址:但是,如果你保持圖像設置爲不重複那麼你的代碼,如下所示修改腳本*/

// Global Variables 

var scrollSpeed = 50; 
// set the default position 
var current = 0; 
// image height & rotation complete 
var _ht,_finishNRot=false; 
// set the direction 
var direction = 'h'; 
// create hidden image element to grab height of it for calculation purpose 
var url = $('body').css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, ''); 
var bgImage = $('<img />'); 
bgImage.hide().bind('load', function(){ _ht = $(this).height(); }); 
$('body').append(bgImage); 
bgImage.attr('src', url); 

function bgscroll() { 
// while rotation not completed 
if(_finishNRot==false){ current -= 1;} else {current+=1; } ; 
// -ve Rotation completed 
if(-(current)==_ht)_finishNRot = true; 
// +ve Rotation completed 
if((current)==0)_finishNRot = false; 
// move the background with backgrond-position css properties 
$('body').css("backgroundPosition", (direction == 'h') ? current + "px 0" : "0 " + current + "px"); 
} 

//Calls the scrolling function repeatedly 
setInterval(bgscroll, scrollSpeed); 

希望這可以幫助你。

乾杯, Ashok

+0

非常感謝你Ashok!你的代碼完美工作。 – user3375954

+0

嗨,我有一個代碼中的問題,當我有一個1024或1480的屏幕分辨率的背景圖像沒有到達其最終像素(水平)或超過其最終像素(水平),我怎麼能解決呢? 下面是一個例子在線:http://www.ideas-web.net63.net/prueba/prueba.html – user3375954

0

取決於如果我明白你的需要和圖像的高度;嘗試使用'background-repeat y'並且不修復你的CSS中的背景圖片。這應該允許您通過圖像,同時鑑於

0

你的意思是優雅的,因爲這東西它的滾動:http://jsfiddle.net/NicoO/fMHL4/ 我確實喜歡這樣的頁面上閱讀;)

@keyframes move-body-bg 
{ 
    0% { background-position:left top; } 
    50% { background-position:left bottom; } 
    100% { background-position:left top; } 
} 

html,body 
{ 
    margin: 0; 
    padding: 0; 
    height: 100%; 
    background-image: url(http://www.placehold.it/800x2000); 
    transition-property: background-position; 

    -webkit-animation: move-body-bg 2s infinite; 
    -moz-animation: move-body-bg 2s infinite; 
    -o-animation:  move-body-bg 2s infinite; 
    animation:   move-body-bg 2s infinite; 
}