【问题标题】:scroll bar is moving to top when button click event is fires. I want to stop scroll bar movement at particular positon触发按钮单击事件时,滚动条移动到顶部。我想在特定位置停止滚动条移动
【发布时间】:2018-10-13 13:57:20
【问题描述】:

实际上,我通过单击按钮在数据库中的表中显示数据。我有多个按钮和多个表格。我想根据按钮单击将滚动条移动到特定的 div。每次当我单击任何按钮时,滚动条都会移到顶部。 这是我用来在特定位置移动滚动条的代码。

<input type="submit"  name="search"  id ="search" onclick="myFunctionq();" value="Display" /> 
<script>
function myFunctionq(){
    var divLoc = $('#div1').offset();
    $('html, body').animate({scrollTop: divLoc.top},"slow");
    };
</script>

这对我不起作用。

如果我在 $(document).ready(function()) 中编写相同的代码,它正在工作并且每次滚动条都在移动。

<script type="text/javascript">
   $(document).ready(function(){
       var divLoc = $('#div1').offset();
       $('html, body').animate({scrollTop: divLoc.top}, "slow");

  });
</script>

我想根据按钮点击事件将滚动位置移动到 div。

【问题讨论】:

  • 添加return false取消默认事件

标签: javascript jquery


【解决方案1】:

当您单击按钮时,它会调用您的函数并调用事件提交并且您的页面会刷新。您需要添加到 onclick return false 或 e.preventDefault,以禁用默认事件

<input type="submit"  name="search"  id ="search" onclick="return myFunctionq();" value="Display" /> 
<script>
function myFunctionq(){
    var divLoc = $('#div1').offset();
    $('html, body').animate({scrollTop: divLoc.top},"slow");
    return false
    };
</script>
<?php if isset($_POST['search']):?> <script>myFunctionq()</script> <?php endif;?> 

【讨论】:

  • 实际上,我通过单击按钮在数据库中的表中显示数据。如果我使用 e.prevent.Default 数据未显示在表格中。我尝试使用 return false 但滚动条仍然移动到顶部。
  • 这意味着,您需要发送表单数据。然后你需要在刷新页面后调用函数。如果它发布查询,你可以做 你可以从按钮中删除调用函数事件
  • 在添加 后它现在可以工作了很多...
猜你喜欢
  • 1970-01-01
  • 2015-03-16
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 2023-01-06
  • 2016-11-17
  • 1970-01-01
  • 2015-10-18
相关资源
最近更新 更多