2017-04-21 70 views
0

我用這樣一個錨元素:Animate scrollTop在Chrome上不起作用?

<div class="my_centered" id="index_scroll_down_button"> 
    <a href="#" onclick="smooth_scroll('#intro')"> 
     <img src="/static/img/scroll-down-icon.png"> 
    </a> 
</div> 

<div class="indexcontainer container" id="intro"> 
</div> 

其中smooth_scroll函數定義爲:

function smooth_scroll(target){ 
    $('html, body').animate({ 
     scrollTop: $(target).offset().top - 60 
    }, 800); 
} 

這種方法適用罰款的Safari,但似乎並沒有在Chrome上工作? 這裏是我的CSS:

#index_scroll_down_button { 
    position: absolute; 
    bottom: 0px; 
    left: 50%; 
    margin-left: -30px; 
} 
+0

工作正常https://codepen.io/anon/pen/YVWqrG –

回答

1

腳本運行良好,但你要防止默認錨點擊事件,在您的情況下使用:

<a href="#" onclick="smooth_scroll('#intro'); return false;"> 

但是,請嘗試刪除嵌入式腳本做這樣的事情:

$('[data-scrollto]').on('click', function(e) { 
 
    e.preventDefault(); 
 
    var target = $($(this).data('scrollto')); 
 
    $('html, body').animate({ 
 
     scrollTop: target.offset().top - 60 
 
    }, 800); 
 
});
#intro { 
 
    border-bottom: 1px solid black; 
 
} 
 
#content { 
 
    height: 1000px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="intro"> 
 
    Intro 
 
</div> 
 
<div id="content"> 
 
    Content height 1000px. 
 
</div> 
 
<div class="my_centered" id="index_scroll_down_button"> 
 
    <a href="#" data-scrollto="#intro"> 
 
     Scroll top 
 
    </a> 
 
</div>

也在JSFiddle

+0

感謝您的評論......在你的榜樣,你有兩個ID與介紹,這可能會導致一些麻煩。我無法在Chrome中正常工作。我複製了你的例子,但它只適用於Safari瀏覽器?你也可以說幾句話,你爲什麼喜歡你的點擊事件,而不是我的功能? – carl

+0

我刪除了第二個#intro,從上面的示例代碼複製/粘貼,應該在Chrome中工作。我們應該避免設置內聯腳本,樣式相同,都應該在遠程文件中設置。我們應該用class,id或data屬性來標記元素,然後決定如何處理它。這種方式的變化很容易,我們可以做可重用的腳本。但是,這只是一個評論,你的麻煩的關鍵是防止默認錨定點擊行動,對於本地鏈接是跳轉/滾動到元素。 – skobaljic

1

Animate scrolltop在firefox中爲我工作,但不在鉻和邊緣。下面的CSS問題造成的:

html, body { 
    overflow-x: hidden; 
} 
+0

那麼刪除這一點解決了這個問題?看起來他們的代碼中沒有這樣的CSS。請確保你回答了問題,否則預計會添加評論。最好的問候 – YakovL

+0

這個答案現在幫了我,謝謝。 – nanuqcz

相關問題