【问题标题】:jquery scrolltop function on click of a button单击按钮时的jquery scrolltop功能
【发布时间】:2014-05-15 08:13:24
【问题描述】:

我使用 scrolltop 功能在单击按钮时滚动到顶部,但它不起作用?

** jquery ******

jQuery('.scroll').click(function () 
{
  jQuery("html, body").animate({ scrollTop: '#fields2' }, 'slow');

    return false;

   });

***** html 代码 ** ***

  <div id="fields2"> 
      ..............
 ...............

       <input class="send_btn scroll" type="button" value="back"/>
      </div>

【问题讨论】:

  • 试试scrollTop: $('#fields2').offset().top

标签: javascript jquery html


【解决方案1】:

问问你自己吧:scrollTop 是一个属性,表示到文档顶部的距离,以像素为单位

在那里,您要求 jQuery 将 scrollTop 设置为“#fields2”,这是一个字符串。

那么,首先,我猜您尝试检索元素#fields2 与顶部的距离?

这边:$('#fields2').offset().top

jQuery('.scroll, .send_btn').click(function (e) 
{
 e.preventDefault(); 
 var dest = $('#fields2').offset().top;
 jQuery("html, body").animate({ scrollTop:  dest }, 'slow');

 // If you need to submit a form, with an input like : <input type="submit" class="send_btn" value="Submit"/>
 if(jQuery(this).hasClass('send_btn')) { // check if you've clicked on .send_btn
    $(this).parents('#myForm').submit(); // submit the form.
 }


});

注意:我用 e.preventDefault() 替换了 return false。 return false 不是停止火灾事件的标准方法。

编辑: 作为 e.preventDefault();停止元素上的事件,您必须使用 jQuery 手动提交表单,如上面的代码所示。

【讨论】:

  • 它工作得很好,所以谢谢大家。还有一个提交按钮 也应该提交表单并滚动到#fields2。如果我为按钮提供滚动类,则提交功能不起作用。
  • 用您的新问题的解决方案编辑了答案。
  • @mujtaba:如果此答案解决了您的问题,请不要忘记通过选中答案前的复选标记将您的问题标记为已回答。
【解决方案2】:

.offset() 返回元素相对于文档的坐标,顶部参数将为您提供元素沿 y 轴的距离(以像素为单位):

jQuery('.scroll').click(function () 
{
  jQuery("html, body").animate({ scrollTop:  $('#fields2').offset().top }, 'slow');

    return false;

   });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多