一、UI事件(不一定是与用户操作有关的事件)
onload:当页面完全加载后在window上触发图片也可以触发事件
<title>UI</title>
<script>
window.onload = function() {
// 等待页面加载完毕后执行
var dTime = document.getElementById("time");
console.log(dTime);
}
</script>
<style>
.s {
width: 200px;
height: 200px;
background-color: pink;
overflow: scroll;
}
</body>
<script>
var s = document.querySelector(".s");
s.onscroll = function() {
console.log(this.scrollTop);
}
var html = document.querySelector("html");
document.body.onscroll = function() {
console.log("html")
}
</script>
.s .mov {
width: 20px;
height: 2000px;
background-color: cyan;
}
</style>
</head>
<body>
<div id="time">12:00</div>
<div class="s">
<div class="mov"></div>
</div>
onresize: 当窗口大小变化时在window上触发
onscroll: 当用户滚动带滚动条的元素中的内容时,在该元素上面触发
如图所示,代码实现后的效果当滚动到一定的值时,会出现粉色方块,当鼠标点击方块,页面会缓慢的移动到页面顶部
<style>
.move {
width: 200px;
height: 4000px;
background-color: orange;
}
.hj {
width: 100px;
height: 100px;
background-color: hotpink;
position: fixed;
bottom: 50px;
right: 20px;
display: none;
}
</style>
<body>
<div class="move">12sdfgwe fga12sdf gwefga12sd fgwefga12 sdfgwefga12
sdfgwefga1 2sdfgwefga12sd fgwefga12sdf gwefga12sdfg
wefga12sdf gwefga12 sdfgwefga1
2sdfgwefga 12sdfgw efga12s dfgwefg a12sd fgwefgae</div>
<div class="hj"></div>
</body>
<script>
var hj = document.querySelector(".hj");
window.onscroll = function(e) {
if(document.documentElement.scrollTop > 50) {
hj.style.display = 'block';
} else {
hj.style.display = 'none';
}
}
hj.onclick = function() {
move();
}
var timer = null;
function move() {
clearInterval(timer);
var t = 20;
var s = document.documentElement.scrollTop;
var v = s / t;
var count = 0;
timer = setInterval(function() {
count ++;
s -= v;
if (t === count) {
clearInterval(timer);
s = 0;
}
document.documentElement.scrollTop = s;
}, 30)
}
</script>