ins*_*ere 23
在某种程度上,您必须识别可点击元素.我构建了一个示例,它使用class-attribute.
这是完成工作的脚本:
$('html,body').animate({
scrollTop: $(this).offset().top - ( $(window).height() - $(this).outerHeight(true) ) / 2
}, 200);
Run Code Online (Sandbox Code Playgroud)
您尝试的是将容器滚动到页面顶部.您还必须计算和减去容器高度和视口高度之间的差异.除以这两个(因为你想在顶部和底部有相同的空间,你准备好了.
然后将click处理程序添加到所有元素:
$(document).ready(function () {
$('.image').click( function() {
$('html,body').animate({ scrollTop: $(this).offset().top - ( $(window).height() - $(this).outerHeight(true) ) / 2 }, 200);
});
});
Run Code Online (Sandbox Code Playgroud)
设置一些HTML/CSS:
<style>
div.image {
border: 1px solid red;
height: 500px;
width: 500px;
}
</style>
<div class="image">1</div>
<div class="image">2</div>
<div class="image">3</div>
<div class="image">4</div>
<div class="image">5</div>
Run Code Online (Sandbox Code Playgroud)
而且你已经完成了.
亲自尝试http://jsfiddle.net/insertusernamehere/3T9Py/
我知道这个问题已经很老了,但是现在,您可以使用scrollIntoView:
例如:
document.body.scrollIntoView({
behavior: 'smooth',
inline: 'center',
block: 'center'
});
Run Code Online (Sandbox Code Playgroud)
小智 5
HTMLElement.prototype.scrollToCenter = function(){
window.scrollBy(0, this.getBoundingClientRect().top - (window.innerHeight>>1));
}
Run Code Online (Sandbox Code Playgroud)
使用纯 JavaScript 实现垂直方向滚动到中心。在水平方向上也是类似的。我不考虑元素的高度,因为它们可能大于屏幕的高度。
| 归档时间: |
|
| 查看次数: |
27099 次 |
| 最近记录: |