2016-10-31 92 views
0

如果這個問題很蠢,但我對jquery不熟悉,請道歉。在右側滾動按鈕旁邊創建滾動左邊按鈕

我有一個橫向滾動的網頁,上面有兩個按鈕。向右滾動的按鈕可以很好地工作,但向左滾動的按鈕總是會將您帶到頁面的開頭,而不管它是什麼。想知道我的代碼有什麼問題!

網頁:http://alicelanyang.com/richardhyatt/women.html

的腳本,用箭頭按鈕是滾動一個右箭頭鍵向左滾動即離開一個:

$(document).ready(function() { 
    var bodyWidth = $("body").width(), 
    wWidth = $(window).width(), 
    step = 400, 
    arrowButton = $("#arrow-button"), 
    pos = 0; 

arrowButton.click(function() { 
if (pos < bodyWidth) { 
    pos += step; 
} else { 
    pos = 0; 
} 

console.log(pos); 

$('body').animate({ scrollLeft: pos }, 1000); 
    }); 

$(document).ready(function() { 
    var bodyWidth = $("body").width(), 
    wWidth = $(window).width(), 
    step = -400, 
    arrowButton = $("#arrow-button-left"), 
    pos = 0; 

    arrowButton.click(function() { 
if (pos < bodyWidth - wWidth) { 
    pos += step; 
} else { 
    pos = 0; 
} 

console.log(pos); 

$('body').animate({ scrollLeft: pos }, 1000); 
    }); 
}); 

任何幫助表示讚賞!

+0

你介意分享你的HTML呢? – Aer0

+0

您的'pos'變量在兩個函數之間是不同的。當你點擊右鍵時,你的位置將變爲400,當你點擊左鍵時,它會變成-400。您需要一個單一的'pos'變量,這兩個函數都可以訪問以保持實際位置。左箭頭應該是'pos - step',右箭頭應該是'pos + step'。 – thepriebe

+0

@thepriebe,這是完全有道理的,我在這裏「去吧!」你有什麼想法如何改變一個位置的代碼,但兩個箭頭按鈕? –

回答

0

錯誤似乎是在你的if else條件。

if (pos < bodyWidth - wWidth) { 
    pos += step; 
} else { 
    pos = 0; 
} 

你總是跳回到你的初始位置,點擊左箭頭。您可以通過pos -= step替換pos = 0

0

你可以嘗試這樣的事情。 https://jsfiddle.net/4yberkho/1/

如果要滾動一個固定值,你可以簡單地通過增加或價值的遞減動畫身體

arrowButtonLeft = $("#arrow-button-left"); 

arrowButton = $("#arrow-button"); 

// Right arrow click 
arrowButton.click(function(){ 

    // Animate the body to scroll right 400px 
    $('body').stop().animate({ scrollLeft: '+=400px' }, 1000); 

}); 

// Left arrow click 
arrowButtonLeft.click(function(){ 

    // Animate the body to scroll left 400px 
    $('body').stop().animate({ scrollLeft: '-=400px' }, 1000); 

}); 
+0

嘿!感謝您的回覆 - 我做出了改變,但它仍然滾動到開始。我也嘗試用post + = step替換第一個pos = 0,但它似乎仍然不工作......任何想法? –

+0

@AliceYang你可以嘗試改變pos + = step;在第二個if語句中pos - = step; ? –

+0

我擺脫了if else語句,但似乎問題在於每個按鈕都有兩個pos值!無論視口在哪裏,左箭頭都會嘗試從pos = 0達到-400。您是否有任何想法知道如何爲兩個按鈕使用一個pos? –

0

下面是POS機變量可能的解決方案基於被改變的步驟和相對位置。

$(document).ready(function() { 
 
var pos = 0; 
 
var step = 400; 
 
var bodyWidth = $("body").width(); 
 
var wWidth = $(window).width(); 
 
var nextArrowButton = $("#arrow-button"); 
 
var backArrowButton = $("#arrow-button-left"); 
 

 
nextArrowButton.click(function() { 
 
\t \t if (pos < bodyWidth) { 
 
    \t \t pos += step; 
 
\t \t } else { 
 
    \t \t pos = 0; 
 
\t \t } 
 
\t \t console.log(pos); 
 
\t $('body').animate({ scrollLeft: pos }, 1000); 
 
    }); 
 

 
backArrowButton.click(function() { 
 
\t \t if (pos < bodyWidth) { 
 
    \t \t pos -= step; 
 
\t \t } else { 
 
    \t \t pos = 0; 
 
\t \t } 
 
\t \t console.log(pos); 
 
\t \t $('body').animate({ scrollLeft: pos }, 1000); 
 
    }); 
 
});

+0

非常感謝!這真太了不起了。 –