JavaScript自学笔记(3)--- 用JS来实现网页浮窗
最近做个小项目,给网页加个浮窗,考验了基础的css,js技术,还是蛮有意思的,代码如下(部分代码来源于引用,见底部)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
*{
padding: 0;
margin: 0;
}
body {
height: 900px;
background-color: white;
}
.fl {
width: 200px;
height: 100px;
background-color:white;
position: fixed;
}
div
{
border-style:solid;
border-top-color:#84C1FF;
border-top-width:22px;
}
</style>
<body>
<div class="fl" id="fl">
<b>注意:</b> "border-top-width" 单独使用没有效果. 要先使用 "border-style" 属性设置 borders.
</div>
</body>
<script language=javascript>
var fl = document.getElementById('fl');
var chroX = document.documentElement.clientWidth;//yemian整个的高宽
var chroY = document.documentElement.clientHeight;
var offsetLeft = fl.offsetLeft;//盒子的位置
var offsetTop = fl.offsetTop;
var timer = 0;//起始秒表为0
//console.log(offsetTop)
var x = 1;//每次移动一
var y = 1;
window.onresize = function(){
chroX = document.documentElement.clientWidth;//yemian整个的高宽
chroY = document.documentElement.clientHeight;
}
function move(){
offsetLeft += x;
offsetTop += y;
fl.style.left = offsetLeft + 'px';
fl.style.top = offsetTop + 'px';
//console.log(chroY)
}
window.onload = function(){
timer = setInterval(function(){
move();
if(offsetTop+200 > chroY || offsetTop < 0){
y = -y;
}
if(offsetLeft+200 > chroX || offsetLeft <0){//如果离网页边框不到200就反方向移动
x = -x;
}
},30)//调整速度,间隔(数字)越大越慢
}
fl.onmouseenter = function(){
clearInterval(timer) //鼠标放在浮窗上就停止移动
}
fl.onmouseleave = function(){//鼠标移开重新开始移动
window.onload();
}
</script>
</html>
大体思路就是设定一个计时器,每到一个时间就重新显示一次窗口,因为你的坐标不同,而且刷新的时间是以毫秒为单位在进行,所以就显示出了一种浮窗的效果。
引用:https://blog.csdn.net/qq_22849785/article/details/93596680