2012-08-10 138 views
0

所以我試圖動畫一個簡單的水平滾動使用jQuery,但它不會觸發,爲什麼?爲什麼我不能讓我的jQuery leftScroll動畫起作用?

http://jsfiddle.net/langoon/b5ZTH/

HTML

<a href="#1">1</a> 
<a href="#2">2</a> 
<a href="#3">3</a> 

<section> 
    <a name="1">1</a> 
    <a name="2">2</a> 
    <a name="3">3</a> 
<section> 

CSS

section { 
    width: 100%; 
    overflow: auto; 
    white-space: nowrap; 
    } 
a[name] { 
    width: 100%; 
    display: inline-block; 
    white-space: normal; 
    } 
a[name='1'] { 
    background-color: green; 
    } 
a[name='2'] { 
    background-color: yellow; 
    } 
a[name='3'] { 
    background-color: red; 
    } 

jQuery的

$('a[href]').click(function(){ 

    $('section').stop().animate({ 
     scrollLeft: $(this.hash).offset().left 
    }, 1000); 

});​ 
+0

它工作正常鉻 – MCSI 2012-08-10 14:15:36

+0

@MCSI不爲我工作,我使用Chrome瀏覽器? – unitario 2012-08-10 14:19:12

回答

0

我解決它改變了jQuery代碼:

$('a[href]').click(function(){ 

    var basePos = $("a[name]").offset().left/-1; // Get position of first a[name] 
    var scrollPos = $("a[name='" + this.hash.replace('#','') + "']").offset().left; 

    $('section').stop().animate({ 
     scrollLeft: basePos + scrollPos 
    }, 'fast'); 

});​ 
1

這可能工作:

var w = []; 
var wt = 0; 

$('section a').each(function(i,v){ 
    (i == 0) ? wt = 0 : wt += $(this).width(); 
    w.push(wt); 
}); 


$('a[href]').click(function(){ 
    var n = this.hash.replace('#',''); 
    var el = $.find("a[name='"+n+"']"); 
    console.log(w[n-1]); 
    $('section').animate({ 
     scrollLeft: w[n-1] 
    }, 1000); 

}); 
+0

感謝您指出正確的方向。但是,您的代碼有限制,例如,它假定「a [href]」和「a [name]」以升序編號命名。我通過將第一個「a [name]」的位置相對於滾動位置指向「a [name]」來解決這個問題。 – unitario 2012-08-15 17:47:04

相關問題