单击后,将元素带到窗口的顶部(带偏移量)

On click, bring element to the top of the window (with offset)

本文关键字:顶部 偏移量 窗口 元素 单击      更新时间:2023-09-26

我想点击这个按钮,它是一个手风琴的部分标题,并将其移动到页面的顶部(基于窗口)

我觉得这很简单——但这是漫长的一天。什么好主意吗?

一些背景是,这是一个类似于手风琴的东西-按钮是标题。因为手风琴很长,而手机屏幕很小,当你折叠打开时……你可能会在某个随机的中间区域结束,我试图让那个区域移动到顶部,而不是散列…我已经尝试了一些散列方法,但我还需要一个if语句来避免在更大的屏幕上发生这种情况。我希望这是清楚的。谢谢。哦,这是小提琴

HTML

<div class="some-div"></div>
<div class="some-div"></div>
<button>button to endup up at top</button>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<button>button to endup up at top</button>


javascript

$('button').on('click', function() {
    $(this). go-to-the-top-with-an-offset-of-10px();  
});

这样,你就可以移动到页面的顶部("based on window"):

$('button').click(function() {   // on button click
    $("html, body").animate({    // catch the `html, body`
        scrollTop:0              // make their `scrollTop` property 0, to go at the top
    }, 1000);                    // in 1000 ms (1 second)
});

演示

如果你想向上移动10px的偏移量,使用:

$('button').click(function () { // on button click
    $("html, body").animate({ // catch the `html, body`
        scrollTop: $(this).offset().top - 10 // button's offset - 10 
    }, 1000); // in 1000 ms (1 second)
});

演示

或者假设你想把第8个div放到顶部点击,使用:

$('button').click(function () { // on button click
    $("html, body").animate({ // catch the `html, body`
        scrollTop: $("div:nth-of-type(8)").offset().top // 8th div's top offset
    }, 1000); // in 1000 ms (1 second)
});
演示