我需要确保特定行在用户加载页面时可见,即使该行在页面后面出现了很多行。换句话说,当页面加载时,它会立即跳转到该标记行。该行只需要位于浏览器窗口可见屏幕内的某个位置。它是这样标记的:
<div class="scrollhere">This line should always be visible when the page loads.</div>
- 只有其中一个出现在整个页面上。
- 我无法编辑标记文本的 HTML,但可以编辑文档开头的 CSS 和 JavaScript。
- 我的意思不是只移动特定行,即使用
position:absolute
。 ,但页面加载到该行。
我怎样才能使页面加载到页面的中间位置,无论哪里有特定的 <div class="scrollhere">
找到了吗?
最佳答案
因此,如果您根本无法编辑 HTML,则需要使用 JavaScript 或 jQuery。这是我用来滚动到元素的函数。
Javascript
这将在 DOM 中查询所有具有您的类 scrollhere
的元素。我们将只选择数组中的第一项(转到第一个元素)。然后我们将使用 scrollIntoView()
.
document.getElementsByClassName('scrollhere')[0].scrollIntoView()
jQuery
/*
* A scrollTo function that gets passed a selector (ID, class, element) & an optional offset
*
* @param {string} location ('#resultsTop')
* @param {integer} offset (-100)
*/
function scrollTo(location, offset) {
$("html, body").animate({scrollTop: ($(location).offset().top + (offset || 0) )}, "slow");
return false;
};
在您的情况下,您将按如下方式调用此函数:
scrollTo('.scrollhere');
您还可以选择传入一个偏移量
。所以也许您不想滚动到该元素的顶部。但宁愿滚动到它上方的 100 像素
。
scrollTo('.scrollhere',-100);
由于您无法编辑 HTML,因此您肯定希望使用监听器。
$(document).ready(function(){
scrollTo('.scrollhere',-100);
});
关于javascript - 如何使页面加载时向下滚动到<div>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25734008/