【问题标题】:Issue with Show/Hide function in jQuery. Jumps to top of pagejQuery 中显示/隐藏功能的问题。跳转到页面顶部
【发布时间】:2013-11-02 07:13:20
【问题描述】:

我正在为我的问题和答案页面使用点击/隐藏功能。但是,当我单击问题以显示答案时,它会跳回顶部。我需要做什么才能停止。

这是我的编码:

脚本:

<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".sub").hide();
//toggle the componenet with class msg_body
jQuery(".cthrough").click(function()
{
jQuery(this).next(".sub").slideToggle(500);
});});
</script>

CSS:

.cthrough {
    display: inline-block;
    font-size: 15px;
    font-family: 'Anaheim', sans-serif;
    text-transform: uppercase;
    letter-spacing: 0px;
}

.sub {
    display: inline-block;
    font-size: 13px;
    padding-left: 10px;
}

HTML:

<a href="#" class="cthrough">This is my question</a>
<div class="sub">
    This is my answer.
</div>

我已尝试将 a href=# 转换为 div 类,但这不会使问题可点击。我也试过把#去掉,但也没有用。

【问题讨论】:

标签: jquery html click hide


【解决方案1】:

如果我申请持续时间说slideDown(),也会遇到同样的麻烦和e.preventDefault() 对我不起作用。

有点老套,但这对我有用。
浏览器在试图计算您在动画期间显示的元素的大小时会发疯。
所以,我马上显示它,现在浏览器知道它的大小了。
但是不透明度很低,然后我只是淡入。

// show/hide jobs section
$('.job').hide();

$('a.jobTrigger').click(function(e){
    $('.job').hide();
    $(this).next('.job').show(0, function() {
        
        //animation to stop page jump
        $(this).css('opacity' , '.1');
        $(this).animate({
            opacity: 1
        });
    });
    e.preventDefault(); //keeps hash out of URL
});

【讨论】:

    【解决方案2】:

    #href 中的根本原因。如果 URL 包含 # 后跟 div 名称,则用户将登陆该 div。这是浏览器的默认行为,在上述情况下,当单击该 URL # 时,会将其附加到根 URL,这就是它位于页面顶部的原因。

    要解决此问题,请删除 href="#" 并使用 style="cursor: pointer" 将手/指针符号保留到该链接。

    而不是&lt;a href="#" class="cthrough"&gt;This is my question&lt;/a&gt; 使用&lt;a class="cthrough"&gt;This is my question&lt;/a&gt; 并将cursor: pointer 样式添加到该类(.cthrough)。

    【讨论】:

      【解决方案3】:

      保留您的href="#" 并使用jQuery's .preventDefault() 以防止跳回顶部的默认操作。

      jQuery(".cthrough").click(function(e) {
          e.preventDefault();  // <-- first line
          jQuery(this).next(".sub").slideToggle(500);
          ...
      

      【讨论】:

      • 谢谢,效果很好! Tessa Wilde,请奖励 Sparky 的回答!
      猜你喜欢
      • 2012-10-05
      • 1970-01-01
      • 2011-07-17
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 2013-03-20
      • 2015-10-07
      相关资源
      最近更新 更多