如何在使用“显示和隐藏锚定标记”时防止滚动页面

How to prevent scrolling of page while using Show and Hide anchor tag?

本文关键字:滚动 隐藏 显示      更新时间:2023-09-26

我对一些数据使用显示和隐藏锚点标记。但每次我点击"显示"或"隐藏"标签时,页面都会回到顶部,我必须向下滚动才能查看详细信息。如何防止这种情况发生,请指导我。我正在使用javascript函数来显示和隐藏详细信息。

<script type="text/javascript">
$(document).ready(function () {
    $(".productDescription").hide();
    $(".show_hide").show();
    $(".hide_show").hide();
    $('.show_hide').click(function () {
        $(this).parent().find('.productDescription').slideToggle();
        $(this).parent().find(".show_hide").hide();
        $(this).parent().find(".hide_show").show();
    });
    $('.hide_show').click(function () {
        $(this).parent().find('.productDescription').slideToggle();
        $(this).parent().find(".show_hide").show();
        $(this).parent().find(".hide_show").hide();
    });
});
</script>

这是我的aspx页面

<div class="product clearfix"> <a href="#" class="show_hide" style="color: #FF0000" id="FD">Full Description</a>
    <br /> <a href="#" class="hide_show" style="color: #FF0000" id="HFD">Hide Full Description</a>
    <div class="productDescription">
        <p>
            <asp:Label ID="im_url" runat="server" Text='<%# Eval("description") %>'></asp:Label>
        </p>
    </div>
</div>

你能试着这样添加preventDefault吗?由于锚标记的href有#,#被附加到url并执行锚标记的默认行为。

$('.show_hide').click(function (evt) {
  evt.preventDefault();
  $(this).parent().find('.productDescription').slideToggle();
  $(this).parent().find(".show_hide").hide();
  $(this).parent().find(".hide_show").show();
});

您必须使用preventDefault(防止本地行为)方法,如下所示:

$('.show_hide').click(function (ev) {
    ev.preventDefault();
    // Your code goes here
})