2016-02-19 70 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); 
});