簡體   English   中英

jQuery不滾動到錨標記

[英]jQuery not scrolling to anchor tag

我似乎無法以我想要的方式獲得此功能。 我希望用戶單擊一個鏈接,在這種情況下,“ Learn More然后打開一個選項卡並將頁面向下滾動到該選項卡所在的位置。 我具有打開選項卡的功能,但無法滾動。 我唯一可以真正滾動的就是復制:

jQuery(document).scrollTop( jQuery("#" + descriptionID).offset().top );

進入chrome的控制台並激活它。 以下是完整的代碼:

jQuery(document).on("click", ".learnMore", function() {
    description = jQuery("a.ui-tabs-anchor:contains('Description')").parent().index();
    descriptionID = jQuery("a.ui-tabs-anchor:contains('Description')").attr('id');
    jQuery(".ui-widget").tabs("option", "active", description);
    jQuery(document).scrollTop( jQuery("#" + descriptionID).offset().top );
});

這是小提琴的鏈接

這是因為當您單擊鏈接時,它會觸發哈希更改。 由於沒有錨,因此您調用scrollTop 之后 ,它會滾動到頂部。 添加return false; 直到您的點擊事件結束或添加e.preventDefault(); 對於更現代的瀏覽器,應更正此問題。

http://jsfiddle.net/jmarikle/dL41forj/

jQuery(document).on("click", ".learnMore", function() {
    ...
    return false;
});

要么

jQuery(document).on("click", ".learnMore", function(e) {
    e.preventDefault();
    ...
});

設置超時並定位正文也可以: http : //jsfiddle.net/o2whkLyu/1/

$(document).on("click", ".learnMore", function() {
    description = jQuery("a.ui-tabs-anchor:contains('Description')").parent().index();
    descriptionID = jQuery("a.ui-tabs-anchor:contains('Description')").attr('id');
    jQuery(".ui-widget").tabs("option", "active", description);
    setTimeout (function(){
        $('body').scrollTop( $("#" + descriptionID).offset().top );}, 20);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM