[英]On click, bring element to the top of the window (with offset)
I want to click this button, which is a section head of an accordion and have it move to the top of page (based on window) 我想单击此按钮,它是手风琴的一个小节,然后将其移到页面顶部(基于窗口)
I feel like this is simple --- but it was a long day. 我觉得这很简单---但那是漫长的一天。 Any ideas?
有任何想法吗?
Some background is that this is an accordion like thing - and the buttons are headers. 一些背景是,这就像手风琴一样-按钮是标题。 Because the accordion is long - and the phone screen is small --- when you fold and open... you can end up in some random middle area of a section and I'm trying to get that section to move to the top instead of a hash... I've tried a few hash ideas, but I'll also need an if statement to avoid this happening on larger screens.
因为手风琴很长-手机屏幕很小-折叠和打开时...您可能会出现在某个区域的某个随机中间区域,而我正试图让该区域移到顶部哈希...我已经尝试了一些哈希思想,但是我还需要一个if语句来避免在更大的屏幕上发生这种情况。 I hope that is clear.
我希望这很清楚。 Thanks.
谢谢。 OH and HERE is a fiddle
哦,在这里是一个小提琴
HTML 的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 javascript
$('button').on('click', function() {
$(this). go-to-the-top-with-an-offset-of-10px();
});
With this, you can move at the top of the page ("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)
});
Or if you want to move up by an offset of 10px, use: 或者,如果您想向上偏移10像素,请使用:
$('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)
});
Or let's say you want to bring the 8th div to the top on click, use: 或假设您想将第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)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.