在jQuery中显示/隐藏功能的问题。跳到页面顶部

时间:2013-10-23 20:10:15

标签: jquery html click hide

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

这是我的编码:

脚本:

<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类但不会使问题可以点击。我也尝试过#out,但这也没有帮助。

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

productInfo.forEach(product => () { console.log(product.ProductID) }) # 的根本原因。如果 URL 包含 href 后跟 div 名称,则用户将登陆该 #。这是浏览器的默认行为,在上述情况下,当点击 URL div 附加到根 URL 时,这就是为什么它位于页面顶部。

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

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

答案 2 :(得分:0)

如果我使用持续时间来说一个slideDown(),那么同样的麻烦和e.preventDefault()对我不起作用。

有点hacky,但这对我有用。 浏览器试图计算动画期间显示的元素的大小。 所以,我马上展示它,现在浏览器知道它的大小。 但是低透明度然后我就把它淡化了。

// 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
});