飘窗实现方法
飘窗即在页面上飘来飘去的窗口。要实现这种效果主要就是改变div距离浏览器左边和上面的距离。
html部分:
<div id="floatWindow">
<div class="title">
<a href="https://www.baidu,com" target="_blank" title="三位一体招生">
<img src="../img/floatwindow.jpg"> //此处只在飘窗内放了一张图作为内容
</a>
</div>
<div class="close">
<p>×关闭</p>
</div>
</div>
css部分:
#floatWindow{
width: 240px;
height: 160px;
position: absolute;
z-index: 9999; //让飘窗飘在最最最上面
}
#floatWindow .title img{
width: 240px;
height: 140px;
}
#floatWindow .close{
text-align: right;
width: 240px;
cursor: pointer;
}
效果图:
js部分:
var floatWindow = document.getElementById("floatWindow"); //获取飘窗div
//飘窗位置变化
var step_x = 1; //飘窗在x轴方向每次移动距离
var step_y = 1; //飘窗在y轴方向每次移动距离
//定义函数
function windowFloat() {
var x = floatWindow.offsetLeft; //获取飘窗距离左边的距离
var y = floatWindow.offsetTop; //获取飘窗距离上边的距离
var x_win = window.innerWidth; //获取浏览器窗口的宽
var y_win = window.innerHeight; //获取浏览器窗口的高
x += step_x;
y += step_y;
if (x <= 0 || x >= x_win - floatWindow.offsetWidth) { //判断飘窗是否碰到最左边或者最右边,碰到则改变移动方向
step_x *= -1;
x += step_x;
}
if (y <= 0 || y >= y_win - floatWindow.offsetHeight) { //判断飘窗是否碰到最上边或者最下边,碰到则改变移动方向
step_y *= -1;
y += step_y;
}
floatWindow.style.left = x + "px";
floatWindow.style.top = y + "px";
}
var timeId2=setInterval(windowFloat, 10);
//鼠标放在上面时飘窗停止移动
floatWindow.onmouseover = function () {
clearInterval(timeId2);
}
//鼠标离开后飘窗开始移动
floatWindow.onmouseout = function () {
timeId2=setInterval(windowFloat, 10); //注意一定要把这个定时器返回的id值命名为清除定时器里的变量名
}
//关闭飘窗
$(document).ready(function () {
$(".close").click(function () {
$("#floatWindow").hide();
});
});
其余小问题总结:
1、在做一个网页的js时经常会用到很多变量,要注意不能重名,这时候不一定会报错,但结果往往是不正确的;
2、position属性的relative和absolute要区分清楚合理运用;
3、对一些细节内容把握还不够,例如z-index要与position一起使用才有效,这些细节问题还需要加强;
4、在使用定时器时一定要注意定时器的id值,清除定时器时一定要对应好该定时器的id值。