1.向下滑动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>向下滑动</title>
<style>
body {
margin: 0px;
}
#show {
width: 200px;
/* 高度为 0 */
height: 100px;
background-color: lightcoral;
margin: 0 auto;
/* 设置为隐藏 */
/*display: none;*/
}
</style>
</head>
<body>
<div id="show"></div>
<script>
var show = document.getElementById('show');
/*show.style.display = 'block';
var t = setInterval(function(){
var style = window.getComputedStyle(show,null);
var height = parseInt(style.height);
// 判断当前的高度是否为 400
if (height >= 400){
clearInterval(t);
} else {
height++;
show.style.height = height + 'px';
}
},50);*/
slideDown(show,400);
/*
将上述实现的向下滑动效果,封装在一个固定的函数中
* 设计当前实现向下滑动效果函数的形参
* elem - 表示实现向下滑动效果的元素
* maxHeight - 表示元素向下滑动的最大高度值
* 函数的逻辑与默认设置CSS样式属性的值无关
*/
function slideDown(elem, maxHeight){
// 操作的元素默认的display值为none
elem.style.display = 'block';
elem.style.height = '0px';
var t = setInterval(function(){
var style = window.getComputedStyle(elem,null);
var height = parseInt(style.height);
// 判断当前的高度是否为 400
if (height >= maxHeight){
clearInterval(t);
} else {
height++;
elem.style.height = height + 'px';
}
},50);
}
</script>
</body>
</html>
2.移动效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>移动效果</title>
<style>
body {
margin: 0px;
}
#box {
width: 100px;
height: 100px;
background-color: lightcoral;
position: absolute;
left: 100px;
top: 100px;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var box = document.getElementById('box');
box.onclick = function(){
clearInterval(t);
}
/*
* 向右移动
* 当前元素移动到页面的最右边时 -> 向左移动
* 向左移动
* 当前元素移动到页面的最左边时 -> 向右移动
*/
var flag = false;// 默认表示向右
var speed = 1;// 表示每次变化的值
t = setInterval(function(){
//speed += 0.01;
// 获取当前页面的宽度
var WIDTH = window.innerWidth;
var style = window.getComputedStyle(box,null);
var left = parseInt(style.left);
var width = parseInt(style.width);
// 判断当前元素移动的方向
if (flag){// 向左移动
left -= speed;
} else {// 向右移动
left += speed;
}
// 判断什么情况下,向左移动;判断什么情况下,向右移动
if ((left + width) >= WIDTH){// 向左移动
flag = true;
} else if (left <= 0){// 向右移动
flag = false;
}
box.style.left = left + 'px';
},10);
</script>
</body>
</html>
内容版权声明:除非注明,否则皆为本站原创文章。
