这两种是一样的吗? $(window).scroll(function(){ }) 原生要怎么写
$(window).scroll(function(){ })
window.onscroll = function(){ }
想要滚动到达顶部时固定在顶部,不到达时不固定,下面不正常,怎么改。兼容Chrome就行,原生的。谢谢
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.fixed{
position: fixed;
top: 0;
}
</style>
</head>
<body>
<div style="height:200px;background-color:#EFE4B0;"></div>
<div id="fixed" style="height:40px;width:100%;background-color:#7092BE;color:#fff;">这个div到达顶部时悬浮在顶部,不到顶部不悬浮</div>
<div style="height:2000px;background-color:#C3C3C3;"></div>
</body>
<script type="text/javascript">
var fixedDom = document.getElementById('fixed');
document.addEventListener('scroll',winScroll,false);
function winScroll(e){
if(fixedDom.offsetTop < document.body.scrollTop){
fixedDom.classList.remove("fixed");
};
if(fixedDom.offsetTop > document.body.scrollTop){
fixedDom.classList.add("fixed");
};
}
</script>
</html>
$(window).scroll(function(){ })的原生代码可以这样子写:
javascript
window.addEventListener('scroll',winScroll); function winScroll(e){ // 拿到e之后进行你需要的处理 }
你给出的两个代码是一样的意思。
根据你的代码稍微调整一下如下,你试试看能否运行:
html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .fixed{ position: fixed; top: 0; } </style> </head> <body> <div style="height:200px;background-color:#EFE4B0;"></div> <div id="fixed" style="height:40px;width:100%;background-color:#7092BE;color:#fff;">这个div到达顶部时悬浮在顶部,不到顶部不悬浮</div> <div style="height:2000px;background-color:#C3C3C3;"></div> <script type="text/javascript"> var fixedDom = document.getElementById('fixed'); window.addEventListener('scroll',winScroll); function winScroll(e){ var top = getElementViewTop(fixedDom); top < 0 ? fixedDom.classList.add("fixed") : fixedDom.classList.remove("fixed"); } function getElementViewTop(element){ var actualTop = element.offsetTop, elementScrollTop=document.body.scrollTop; return actualTop-elementScrollTop; } </script> </body> </html>