Javascript 滚动回一个DIV';来自JS/Jquery的位置

Javascript 滚动回一个DIV';来自JS/Jquery的位置,javascript,jquery,html,jquery-mobile,Javascript,Jquery,Html,Jquery Mobile,我有一系列可展开的内容DIV,它们最初是折叠的,单击另一个带有标题文本的DIV时会展开。请参阅下面的代码示例 <div id="post"> <div class="heading" onclick="opendiv()">...Heading...</div> <div class="body">.....Lengthy content.....</div> </div> .... .... 您没有向.bod

我有一系列可展开的内容DIV,它们最初是折叠的,单击另一个带有标题文本的DIV时会展开。请参阅下面的代码示例

<div id="post">
   <div class="heading" onclick="opendiv()">...Heading...</div>
   <div class="body">.....Lengthy content.....</div>
</div>
....
....

您没有向
.body
div添加任何事件侦听器

<div class="body" onclick="gotoHead()">.....Lengthy content.....</div>

根据您的描述,您编写脚本的方式存在一些问题。一是.body div没有单击事件。二是将javascript单击事件直接编码到HTML中。通常,除非必须这样做,否则最好在JavaScript中声明事件,这通常更容易返回并编辑新功能

以下是您所做工作的更新:

$('.heading').click(function(e){
    // hide or show the corresponding .body div
    $(this).parent().children('div.body').toggle();
});

$('.body').click(function(e){
    // scroll to the corresponding .heading div
    $('html,body').animate({
        scrollTop: $(this).parent().children('div.heading').offset().top
    }); 
});
您还可以在此处看到这一点:

由于ID是uniq,因此无需将标记名放在选择器前面
$(“#post div.heading”)
滚动到div可以使用此代码(当然是在单击
.header
之后,而不是像您所说的
.body
,这是因为实现错误。请查看下面的答案)。如果您使用的是jQM,请使用
$.mobile.silentScrol()
function gotoHead() {
    document.body.scrollTop = $('#post .heading').offset().top;
}
$('.heading').click(function(e){
    // hide or show the corresponding .body div
    $(this).parent().children('div.body').toggle();
});

$('.body').click(function(e){
    // scroll to the corresponding .heading div
    $('html,body').animate({
        scrollTop: $(this).parent().children('div.heading').offset().top
    }); 
});