本文主要是介绍javascript onscroll,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
定义和用法
onscroll 事件在元素滚动条在滚动时触发。
提示: 使用 CSS overflow 样式属性来创建元素的滚动条。
语法
HTML 中:
JavaScript 中:
JavaScript 中, 使用 addEventListener() 方法:
object.addEventListener("scroll", myScript);技术细节
是否支持冒泡: | Yes |
---|---|
是否可以取消: | No |
实例1:
<!DOCTYPE html>
<html>
<head>
<style>
div {border: 1px solid black;width: 200px;height: 100px;overflow: scroll;
}
</style>
</head>
<body>
<p>尝试滚动 div。</p>
<div οnscrοll="myFunction()">In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'</div>
<p>滚动 <span id="demo">0</span> 次。</p>
<script>
x = 0;
function myFunction() {document.getElementById("demo").innerHTML = x += 1;
}
</script>
</body>
</html>
运行结果:
实例2:
利用 onscroll 事件检测滚动条位置,当向下滚动到一定位置时,在页面右下角会出现“返回顶部”的锚链接
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
#top_div{position:fixed;bottom:80px;right:0;display:none;
}
</style><script type="text/javascript">window.onscroll = function(){var t = document.documentElement.scrollTop || document.body.scrollTop; var top_div = document.getElementById( "top_div" );if( t >= 300 ) {top_div.style.display = "inline";} else {top_div.style.display = "none";}
}</script></head>
<body>
<a name="top">顶部<a>
<div id="top_div"><a href="#top">返回顶部</a></div>
<br />
<br />
......
这里尽量多些<br />以便页面出现滚动条,限于篇幅本文此处略去
</body>
</html>
为窗口添加滚动条事件:
var scrolltop=document.documentElement.scrollTop||document.body.scrollTop;
实例3:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
#box{ height:50px; width:200px; background:#666; position:absolute; left:0px; top:0px;}
</style>
</head>
<body style="height:9000px;">
<div id="box"></div><script language="javascript">
window.onscroll = function(e){
var e =e || window.event;
var scrolltop=document.documentElement.scrollTop||document.body.scrollTop;var box = document.getElementById('box');
box.style.top = scrolltop+'px';
//console.log(scrolltop);
}
</script>
</body>
</html>
参考:http://www.runoob.com/jsref/event-onscroll.html
http://www.5idev.com/p-javascript_events_onscroll.shtml
http://www.zixuephp.com/html/javascript/2014_11/4040.html
这篇关于javascript onscroll的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!