2016-02-19 77 views
1

我真的是新來的JQuery和SO。總是在這裏找到很好的幫助,但現在我真的需要一些幫助。替換<a>與<label> jquery動畫滾動

我在SO上發現此鏈接,Smooth scrolling when clicking an anchor link,它很棒,直到我嘗試用label標記替換它。我嘗試了幾件事,並搜索了很多。我希望我不會錯過明顯的東西..無論如何,這裏是代碼。

<head> 
<script type="text/javascript"> 
$('label').click(function(){ 
$('html, body').animate({ 
scrollTop: $($.attr(this, 'onclick')).offset().top 
}, 500); 
return false; 
}); 
</script> 
</head> 

<body> 

<!--(START) THIS IS THE LABEL I WANT TO CLICK (START)--> 
<div id="top"> 
    <input type="checkbox" class="toggle" id="button"> 
     <label class="linkbutton" onclick="window.location.href='#SCROLL'" for="button"> 
      <h2>Click This Text = Scroll Down</h2> 
     </label> 
</div> 
<!--(START) END OF LABEL (START)--> 

<div id="left"></div> 
<div id="mid-container"> 

<!--(END) WHERE I WANT TO GO SMOOTHLY(END)--> 
<div class="mid"> 
    <div class="section"><label id="SCROLL"></label> 
     <h2>This is the section I want to go to.... SMOOTHLY</h2> 
    </div> 
</div> 
<!--(END) WHERE I WANT TO GO SMOOTHLY (END)--> 

</body> 
</html> 

該標籤指引我到我想去的地方,但沒有任何平滑度。 感謝您的幫助。

回答

0

可以使用自定義屬性data-持有href值要滾動到:

HTML

<div id="top"> 
    <input type="checkbox" class="toggle" id="button"> 
    <label class="linkbutton" data-href="#SCROLL" for="button"> 
    <h2>Click This Text = Scroll Down</h2> 
    </label> 
</div> 
<!--(START) END OF LABEL (START)--> 

<div id="left"></div> 
<div id="mid-container"> 

<div class="mid"> 
    <div class="section"><label id="SCROLL"></label> 
     <h2>This is the section I want to go to.... SMOOTHLY</h2> 
    </div> 
</div> 

jQuery的

$('label').click(function() { 
     href = $(this).data('href'); 
     $('html, body').animate({ 
     scrollTop: $(href).offset().top 
     }, 500); 
     return false; 
    }); 

Check the example

+0

非常感謝。那正是我想要的。非常感激。 –

0

HTML

<label class="linkbutton" data-href="#SCROLL" for="button"> 

JS

$('label').click(function(){ 
    $('html, body').animate({ 
     scrollTop: $($(this).data('href')).offset().top 
    }, 500); 
});