我意识到这个问题之前已被问过 - 但我已经搜遍了几乎所有我能找到的东西 - Incredible Things
这是我的http://shoelesstestblog.blogspot.com
这是代码
<div id="myElement">
<div id="nav">
<a href="">Home</a>
</div>
</div>
<style>
#myElement {
background-color: #fff;
color: #fff;
font-family: 'Bitter';
font-size: 13px;
letter-spacing: 1px;
line-height: 40px;
margin-left: -180px;
opacity: 0.9;
text-align: center;
text-transform: uppercase;
width: 1280px;
word-spacing: 20px;
z-index: 5000;
}
</style>
<script type="text/javascript">
var yPosition; // save original y position of element here
window.onload = function(){ // once entire page is loaded this function is fired
// save original y position of element before it is scrolled
yPosition = document.getElementById("myElement").offsetTop;
}
window.onscroll = function(){ // scrolling fires this function
var myElement = document.getElementById("myElement"); // for cleaner code
// compare original y position of element to y position of page
if( yPosition <= window.pageYOffset ){
// snap element to the top by changing css values of element
myElement.style.position = "fixed";
myElement.style.top = "0px";
}
else {
// re-position to original flow of content
myElement.style.top = ""; // set to default
}
}
</script>
答案 0 :(得分:2)
如果要修复到页面顶部的元素为<div id="myElement">
,我建议您将属性position:fixed;
添加到元素的相应CSS中。
#myElement {
left: 0px;
top: 0px;
position:fixed;
background-color: #fff;
color: #fff;
font-family: 'Bitter';
font-size: 13px;
letter-spacing: 1px;
line-height: 40px;
margin-left: -180px;
opacity: 0.9;
text-align: center;
text-transform: uppercase;
width: 1280px;
word-spacing: 20px;
z-index: 5000;
}
</style>
我还添加了属性left: 0px; top: 0px;
来确定屏幕上的元素位置。
答案 1 :(得分:0)
position:fixed;
可以实现你想要的目标