javascript - 单击时,将元素带到窗口顶部(带偏移)

标签 javascript jquery html

我想单击这个按钮,它是 Accordion 的节头,并将其移动到页面顶部(基于窗口)

我觉得这很简单——但这是漫长的一天。有什么想法吗?

一些背景是,这是一个类似 Accordion 的东西 - 按钮是标题。因为 Accordion 很长 - 而且手机屏幕很小 - 当你折叠和打开时......你可能会出现在某个部分的随机中间区域,而我试图让该部分移动到顶部哈希...我尝试了一些哈希想法,但我还需要一个 if 语句来避免在较大屏幕上发生这种情况。我希望这是清楚的。谢谢。哦和HERE is a fiddle

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

最佳答案

这样,您就可以在页面顶部移动(“基于窗口”):

$('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)
});

DEMO

或者,如果您想向上移动 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)
});

DEMO

或者假设您想在单击时将第 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)
});

DEMO

关于javascript - 单击时,将元素带到窗口顶部(带偏移),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22726542/

相关文章:

javascript - 滚动条上的水平移动

html - 仅 CSS 的全宽侧边栏背景可能吗?

javascript - 重新连接到同一个 Websocket

javascript - AJAX - 跨域不起作用

javascript - Angular Bootstrap DatePicker UTC 错误输出

javascript - jQuery scrollTop 静态元素上的目标引用发生变化

javascript - 如果选中,更改复选框旁边的文本。 HTML + JS 或 jQuery

javascript - 可以在多数组中命名不同的数组吗?

javascript - 如何为使用 L.GeoJSON 创建的每个图层提供不同的选项?

html - 在图像上淡入的点图案叠加