2017-04-04 50 views
0

對於移動設備,我想將所有h1標題轉換爲可平滑滾動到其目標的錨點。爲此,當發生某個設備調整大小時,我只需用a標記包裝h1標記的內容,然後在設備回到桌面寬度時打開a標記的內容。當元素動態包裝爲錨點時,平滑滾動或工作

$(document).ready(function() { 
 
    // Add smooth scrolling to all links 
 
    $("a").on('click', function(event) { 
 

 
    // Make sure this.hash has a value before overriding default behavior 
 
    if (this.hash !== "") { 
 
     // Prevent default anchor click behavior 
 
     event.preventDefault(); 
 

 
     // Store hash 
 
     var hash = this.hash; 
 

 
     // Using jQuery's animate() method to add smooth page scroll 
 
     // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area 
 
     $('html, body').animate({ 
 
     scrollTop: $(hash).offset().top 
 
     }, 800, function() { 
 

 
     // Add hash (#) to URL when done scrolling (default click behavior) 
 
     window.location.hash = hash; 
 
     }); 
 
    } // End if 
 
    }); 
 
}); 
 

 

 
//the function to convert the heading to an anchor for devices smaller than 780px 
 
function makeResponsive() { 
 
    if ($(window).width() < 780) { 
 
    if ($('a').length) { 
 
     return true; 
 
    } else { 
 
     $('h1').each(function() { 
 
     $(this).contents().eq(0).wrap('<a href="#section2"></a>'); 
 
     }); 
 
    } 
 

 

 
    } else { 
 
    $('a').contents().unwrap(); 
 
    } 
 
} 
 

 
//run on document load and on window resize 
 
$(document).ready(function() { 
 

 
    //on load 
 
    makeResponsive() 
 

 
    //on resize 
 
    $(window).resize(function() { 
 
    makeResponsive(); 
 
    }); 
 

 
});
body, 
 
html, 
 
.main { 
 
    height: 100%; 
 
} 
 

 
section { 
 
    min-height: 100%; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h1> 
 
    The Heading 
 
</h1> 
 

 
<div class="main"> 
 
    <section></section> 
 
</div> 
 

 
<div class="main" id="section2"> 
 
    <section style="background-color:blue"></section> 
 
</div>

的問題是,當H1的內容轉換爲錨,平滑滾動是不會發生的一切,錨正好跳到目標。

回答

0

您的a-Tag沒有得到單擊事件,因爲您在不存在偵聽器時添加它。

試試這個

$(document).on('click', 'a', function(event) {... 
0

而不是將它包裝在錨點中,只需將「移動錨點」類添加到這些標題即可。然後,而不是聽關於錨點擊,監聽對「移動錨」和變革點擊:

$('html, body').animate({ 
     scrollTop: $('#section2').offset().top 
}, 800, function() { 

甚至一個簡單的解決方案 - 您對點擊功能非常年底前,增加「返回false ;」所以瀏覽器不會自動向下滾動頁面。

編輯:另外,將所有內容都包含在單個documentReady函數中,並在添加點擊偵聽器之前執行makeResponsive()。