替换<a> with <label> Jquery Animation Scroll

时间:2016-02-19 12:46:12

标签: jquery html jquery-animate smooth-scrolling

I'm really new to JQuery and SO. Always found great help here but now i really need some help.

I found this link here on 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>

标签指示我到我想去的地方,但没有任何顺畅。 谢谢你的帮助。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

HTML

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

JS

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