div
使用位于顶部且在向下滚动时始终可见的 Javascript(或以编程方式的 CSS)构建简单浮动 s 的正确方法是什么?
现在我已经看到了这样的例子。当您向下滚动时,您会看到 div 跳跃和延迟。当页面的内容不是我的时,我希望它始终位于顶部,
脚本将通过 chrome 扩展注入
可以吗?像 这样的东西;但不太复杂,不依赖于页面内容
使用您想要保持在顶部的元素的class
or ,您应该应用一些 CSS 规则,id
例如,如果您的元素类是.topnavigation
您可以在 jQuery 中执行以下操作
<style>
.topnavigation {
width:;/* add the width here */
position:static;
}
.topnavigation.scrolling {
position:fixed;
top:0px;
}
</style>
<script>
$(window).scroll(function () {
if($(this).scrollTop() > 50) // change 50 to what you want (work out how far the nav is from the top of the page alraedy and add it there, that'll make it smoother transition)
{
$('.topnavigation').addClass('scrolling');
} else {
$('.topnavigation').removeClass('scrolling');
}
});
</script>
如果您不能使用 jQuery,您可以使用普通的 javascript 执行以下操作:
更新:2017 年 1 月 6 日 我已经更新了它以使用 document.querySelector 和 Element.classList 方法。所有现代浏览器和 IE 10 > 都支持这些方法。
window.addEventListener('scroll',checkPosition,false);
function checkPosition()
{
// #theid or #theclass or standard element selector
var xNAV = document.querySelector("#topnav");
if(window.scrollY > 50)
{
xNAV.classList.add("scrolling");
} else {
xNAV.classList.remove("scrolling");
}
}
使用 JavaScript,确定您希望它何时浮动,然后添加 css:position:fixed