我正在对我的问题和答案页面使用单击/隐藏功能。但当我单击问题显示答案时,它会跳回到顶部。我要怎么做才能让这一切停止。
这是我的代码:
脚本:
<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>我尝试过将一个href=#转换为一个div类,但这并不能使问题变得可点击。我也试着把#去掉,但也没什么用。
发布于 2013-10-24 04:11:54
保留您的href="#"并使用jQuery's .preventDefault()来防止跳回顶部的默认操作。
jQuery(".cthrough").click(function(e) {
    e.preventDefault();  // <-- first line
    jQuery(this).next(".sub").slideToggle(500);
    ...发布于 2021-04-28 17:14:30
href中#的根本原因。如果URL包含#后跟div名称,则用户将登录到该div。这是浏览器的默认行为,在上面的情况下,当单击URL #被附加到根URL时,这就是为什么它会出现在页面的顶部。
要修复此问题,请删除href="#"并使用style="cursor: pointer"保留指向该链接的手形/指针符号。
使用<a class="cthrough">This is my question</a>代替<a href="#" class="cthrough">This is my question</a>,并将cursor: pointer样式添加到该类(.cthrough)。
发布于 2015-02-19 00:51:33
如果我应用持续时间来表示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
});https://stackoverflow.com/questions/19551371
复制相似问题