我想单击这个按钮,它是 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/