单击“减少”按钮不会将我带回到文档的原始位置

时间:2015-11-24 19:19:58

标签: javascript

当我点击更多按钮时,我的div 1正在替换div 2.大部分时间div2包含大量文本,并且要求用户向下滚动以阅读整个帖子。问题是通过点击较少按钮,我无法恢复帖子的原始位置。以前我尝试通过将其连接到文章标签中的#id来解决此问题,但没有取得多大成功。另外,document.body.scrollTop;不适合我。最后,我通过使用scrollIntoView获得了一些生产力,但它仍然没有解决我的问题。在理想情况下: 1)我希望能够点击“更多”并滚动到帖子的底部 2)我希望能够点击“减少”并导航到所选帖子的顶部

function switchVisible(index, input) {
    var div1 = document.getElementsByClassName('div1')[index];
    var div2 = document.getElementsByClassName('div2')[index];
    if (div1) {
        if (div1.style.display == 'none') {
            div1.style.display = 'block';
            div2.style.display = 'none';
        } else {
            div1.style.display = 'none';
            div2.style.display = 'block';
        }
    }

    if (input.value == "Show More") input.value = "Show Less";
    else input.value = "Show More";
      input.scrollIntoView(false);

}
.hide {display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<article id="myFirst_id">
<div class="div1">
    <p>This is div 1</p>
</div>
<div class="div2 hide">
    <p>Although moreover mistaken kindness me feelings do be marianne. Son over own nay with tell they cold upon are. Cordial village and settled she ability law herself. Finished why bringing but sir bachelor unpacked any thoughts. Unpleasing unsatiable particular inquietude did nor sir. Get his declared appetite distance his together now families. Friends am himself at on norland it viewing. Suspected elsewhere you belonging continued commanded she. 

Of be talent me answer do relied. Mistress in on so laughing throwing endeavor occasion welcomed. Gravity sir brandon calling can. No years do widow house delay stand. Prospect six kindness use steepest new ask. High gone kind calm call as ever is. Introduced melancholy estimating motionless on up as do. Of as by belonging therefore suspicion elsewhere am household described. Domestic suitable bachelor for landlord fat. 

Respect forming clothes do in he. Course so piqued no an by appear. Themselves reasonable pianoforte so motionless he as difficulty be. Abode way begin ham there power whole. Do unpleasing indulgence impossible to conviction. Suppose neither evident welcome it at do civilly uncivil. Sing tall much you get nor. 

Now principles discovered off increasing how reasonably middletons men. Add seems out man met plate court sense. His joy she worth truth given. All year feet led view went sake. You agreeable breakfast his set perceived immediate. Stimulated man are projecting favourable middletons can cultivated. 

Not far stuff she think the jokes. Going as by do known noise he wrote round leave. Warmly put branch people narrow see. Winding its waiting yet parlors married own feeling. Marry fruit do spite jokes an times. Whether at it unknown warrant herself winding if. Him same none name sake had post love. An busy feel form hand am up help. Parties it brother amongst an fortune of. Twenty behind wicket why age now itself ten. 

He oppose at thrown desire of no. Announcing impression unaffected day his are unreserved indulgence. Him hard find read are you sang. Parlors visited noisier how explain pleased his see suppose. Do ashamed assured on related offence at equally totally. Use mile her whom they its. Kept hold an want as he bred of. Was dashwood landlord cheerful husbands two. Estate why theirs indeed him polite old settle though she. In as at regard easily narrow roused adieus. 

Kindness to he horrible reserved ye. Effect twenty indeed beyond for not had county. The use him without greatly can private. Increasing it unpleasant no of contrasted no continuing. Nothing colonel my no removed in weather. It dissimilar in up devonshire inhabiting. 

Advantage old had otherwise sincerity dependent additions. It in adapted natural hastily is justice. Six draw you him full not mean evil. Prepare garrets it expense windows shewing do an. She projection advantages resolution son indulgence. Part sure on no long life am at ever. In songs above he as drawn to. Gay was outlived peculiar rendered led six. 

Repulsive questions contented him few extensive supported. Of remarkably thoroughly he appearance in. Supposing tolerably applauded or of be. Suffering unfeeling so objection agreeable allowance me of. Ask within entire season sex common far who family. As be valley warmth assure on. Park girl they rich hour new well way you. Face ye be me been room we sons fond. 

Adieus except say barton put feebly favour him. Entreaties unpleasant sufficient few pianoforte discovered uncommonly ask. Morning cousins amongst in mr weather do neither. Warmth object matter course active law spring six. Pursuit showing tedious unknown winding see had man add. And park eyes too more him. Simple excuse active had son wholly coming number add. Though all excuse ladies rather regard assure yet. If feelings so prospect no as raptures quitting. 

</p>
</div>
</article>
<input id="show_less" type="button" value="Show More" onclick="switchVisible(0, this);" />
<article id="mySecond_id">
<div class="div1">
    <p>This is div 1</p>
</div>
<div class="div2 hide">
    <p>Although moreover mistaken kindness me feelings do be marianne. Son over own nay with tell they cold upon are. Cordial village and settled she ability law herself. Finished why bringing but sir bachelor unpacked any thoughts. Unpleasing unsatiable particular inquietude did nor sir. Get his declared appetite distance his together now families. Friends am himself at on norland it viewing. Suspected elsewhere you belonging continued commanded she. 

Of be talent me answer do relied. Mistress in on so laughing throwing endeavor occasion welcomed. Gravity sir brandon calling can. No years do widow house delay stand. Prospect six kindness use steepest new ask. High gone kind calm call as ever is. Introduced melancholy estimating motionless on up as do. Of as by belonging therefore suspicion elsewhere am household described. Domestic suitable bachelor for landlord fat. 

Respect forming clothes do in he. Course so piqued no an by appear. Themselves reasonable pianoforte so motionless he as difficulty be. Abode way begin ham there power whole. Do unpleasing indulgence impossible to conviction. Suppose neither evident welcome it at do civilly uncivil. Sing tall much you get nor. 

Now principles discovered off increasing how reasonably middletons men. Add seems out man met plate court sense. His joy she worth truth given. All year feet led view went sake. You agreeable breakfast his set perceived immediate. Stimulated man are projecting favourable middletons can cultivated. 

Not far stuff she think the jokes. Going as by do known noise he wrote round leave. Warmly put branch people narrow see. Winding its waiting yet parlors married own feeling. Marry fruit do spite jokes an times. Whether at it unknown warrant herself winding if. Him same none name sake had post love. An busy feel form hand am up help. Parties it brother amongst an fortune of. Twenty behind wicket why age now itself ten. 

He oppose at thrown desire of no. Announcing impression unaffected day his are unreserved indulgence. Him hard find read are you sang. Parlors visited noisier how explain pleased his see suppose. Do ashamed assured on related offence at equally totally. Use mile her whom they its. Kept hold an want as he bred of. Was dashwood landlord cheerful husbands two. Estate why theirs indeed him polite old settle though she. In as at regard easily narrow roused adieus. 

Kindness to he horrible reserved ye. Effect twenty indeed beyond for not had county. The use him without greatly can private. Increasing it unpleasant no of contrasted no continuing. Nothing colonel my no removed in weather. It dissimilar in up devonshire inhabiting. 

Advantage old had otherwise sincerity dependent additions. It in adapted natural hastily is justice. Six draw you him full not mean evil. Prepare garrets it expense windows shewing do an. She projection advantages resolution son indulgence. Part sure on no long life am at ever. In songs above he as drawn to. Gay was outlived peculiar rendered led six. 

Repulsive questions contented him few extensive supported. Of remarkably thoroughly he appearance in. Supposing tolerably applauded or of be. Suffering unfeeling so objection agreeable allowance me of. Ask within entire season sex common far who family. As be valley warmth assure on. Park girl they rich hour new well way you. Face ye be me been room we sons fond. 

Adieus except say barton put feebly favour him. Entreaties unpleasant sufficient few pianoforte discovered uncommonly ask. Morning cousins amongst in mr weather do neither. Warmth object matter course active law spring six. Pursuit showing tedious unknown winding see had man add. And park eyes too more him. Simple excuse active had son wholly coming number add. Though all excuse ladies rather regard assure yet. If feelings so prospect no as raptures quitting. 


    </p>
</div>
 </article>
<input id="show_less" type="button" value="Show More" onclick="switchVisible(1, this);" />

1 个答案:

答案 0 :(得分:0)

这是对你的问题的一点修改,但如果你稍微修改标记,你可以指定要滚动的目标,组中的容器,然后根据标记中的数据设置隐藏/显示和滚动。

准备好了吗?向右跳到示例fidde:http://jsfiddle.net/MarkSchultheiss/r7q1d8r7/1/

为此,我为所有div对组添加了一个“容器”,然后为我将操作的每个组添加了一个group div:

<div id="showcontainer">
    <div class="showgroup">

我还添加了一些“数据”属性,然后查询滚动目标的属性,并使用一些添加的类设置目标显示/隐藏的兄弟:

修改了标记片段:

<div class="showsmall shown">
    <p>This is div 1</p>
</div>
<div class="hide showbig shown">

带有数据元素的按钮(注意我将您的input更改为按钮)

<button id="show_less" type="button" class='showItem' data-scroll-target=".shown" data-display-target=".shown" data-showvalue="Show More" data-lessvalue="Show Less">Show More</button>

完整加价:

<div id="showcontainer">
    <div class="showgroup">
        <div class="showsmall shown">
            <p>This is div 1</p>
        </div>
        <div class="hide showbig shown">
            <p>...cut out huge text...</p>
        </div>
        <button id="show_less" type="button" class='showItem' data-scroll-target=".shown" data-display-target=".shown" data-showvalue="Show More" data-lessvalue="Show Less">Show More</button>
    </div>
    <div class="showgroup">
        <div class="showsmall shown">
            <p>This is div 1</p>
        </div>
        <div class="hide showbig shown">
            <p>...cut out huge text...</p>
        </div>
        <button id="show_less" type="button" class='showItem' data-scroll-target=".shown" data-display-target=".shown" data-showvalue="Show More" data-lessvalue="Show Less">Show More</button>
    </div>
</div>

代码:

$(document).ready(function () {
    $('#showcontainer').on('click', '.showItem', function (event) {
        var displayTarget = $(this).data('displayTarget');
        var dispTargets = $(this).siblings(displayTarget);
        $(this).siblings(displayTarget).toggleClass('hide');

        //get the scroll target from the button
        var scrollTarget = $(this).data('scrollTarget');
        // hide/show depending on prior state
        if (dispTargets.filter(':visible').hasClass('showsmall')) $(this).text($(this).data("showvalue"));
        else $(this).text($(this).data("lessvalue"));

        // do ths scroll to the scroll target
        var container = $(document.body);
        var scrollTo = scrollTarget == "me" ? $(this) : $(this).siblings(scrollTarget).filter(':visible');

        container.scrollTop(
        scrollTo.offset().top - container.offset().top + container.scrollTop());
    });
});

特别提示:将data-scroll-target=".shown"更改为data-scroll-target="me",它会滚动到按钮而不是其他元素

编辑:“改变尽可能少的标记” - 不是我要做的,但你必须将id="show_less"更改为class="show_less"或页面无效并且不起作用。

然后你可以使用:(但你必须从标记中删除代码或使该函数不执行任何操作)

<input class="show_less" type="button" value="Show More"  />

$(document).ready(function () {
    $('.show_less').on('click', function (event) {
        var dispTargets = $(this).prev().find('.div1, .div2');
        dispTargets.toggleClass('hide');

        var scrollTarget = $(this);//the input field
        // hide/show depending on first div visible state
        if (dispTargets.eq(0).hasClass('hide')) $(this).val("Show Less");
        else $(this).val("Show More");

        // do ths scroll to the scroll target
        var container = $(document.body);
        var scrollTo =  $(this);// the button

        container.scrollTop(
        scrollTo.offset().top - container.offset().top + container.scrollTop());
    });
});