将 <a> 替换为 <label> Jquery 动画卷轴

Replace <a> with <label> Jquery Animation Scroll

我对 JQuery 和 SO 真的很陌生。总是在这里找到很大的帮助,但现在我真的需要一些帮助。

我在 SO Smooth scrolling when clicking an anchor link 上找到了这个 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>

标签将我引导到我想去的地方,但没有任何平滑度。 感谢您的帮助。

您可以使用自定义 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

HTML

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

JS

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