css实现div悬浮层,始终停留在浏览器的最下方,不随页面的滚动条滚动改变位置或消失

html-css016

css实现div悬浮层,始终停留在浏览器的最下方,不随页面的滚动条滚动改变位置或消失,第1张

1、新建一个html文件,命名为test.html。

2、在test.html文件内,使用div标签创建一个div,同时设置其class属性为con,主要用于下面通过该类名进行样式的设置。

3、在test.html文件内,在div内使用p标签创建一段测试文字的显示。

4、在test.html文件内,在div内,再使用div标签创建一个类名为ff的div,用于作为悬浮的div。

5、在test.html文件内,在css标签内,使用“*”初始化元素样式,设置外边距和内边距都为0。同时,设置类名为con的div的样式,设置其背景颜色为灰色,居中对齐,宽度为640px,高度为1000px。

6、在css标签内,再设置类名为ff的样式,设置其高宽都为100px,背景颜色为红色,使用position定位属性设置div在页面的绝对位置,距离页面顶部为20px,距离页面左边为0px,从而实现div悬浮在页面中。

7、在浏览器打开test.html文件,查看实现的效果。

完美的封装了popUpBox这个类

这个类一共两个公开方法

show    显示

hidden    隐藏

其他功能请自行扩展

不敢保证简单,但每一行都写了注释

<!DOCTYPE html>

<html>

<head>

<title>CSS 点击文字或按钮打开div浮动层 </title>

<meta charset="UTF-8" />

</head>

<script>

function popUpBox(){ //创建盒子类

this.init = function(){ //初始化函数

var onloadFunc = window.onload, //将window.onload事件执行的函数保存到onloadFunc

subInit = function(o){ //需要等结构加载完成执行的函数

document.body.appendChild(o.mask) //将遮罩添加到body

document.body.appendChild(o.box) //将盒子添加到body

},

createElement = function(){ //创建元素函数,共同的样式在这里已经设置

var e = document.createElement('div') //创建一个div

e.style.position = 'fixed' //设置定位方式为跟随浏览器移动

e.style.left = '0px' //元素x轴位置

e.style.top = '0px' //元素y轴位置

e.style.zIndex = '2000' //元素z轴位置

e.style.width = window.innerWidth + 'px' //元素宽度

e.style.height = window.innerHeight + 'px' //元素高度

e.style.margin = '0px' //元素的外边距

e.style.padding = '0px' //元素的内边距

e.style.backgroundColor = 'rgba(0, 0, 0, 0.3)' //元素的背景颜色

return e //返回这个元素

}

this.mask = createElement() //创建遮罩

this.mask.onclick = (function(o){ //创建匿名函数 参数一 传入需要操作的对象

return function(){ //匿名函数返回为遮罩绑定鼠标点击事件执行函数

o.hidden() //为o这个对象执行隐藏函数

}

})(this) //立即执行匿名函数 并传入当前对象

this.box = createElement() //盒子

this.box.style.left = window.innerWidth / 2 + 'px' //设置盒子水平居中

this.box.style.top = window.innerHeight / 2 + 'px' //设置盒子垂直居中

this.box.style.width = '400px' //设置盒子宽度

this.box.style.height = '300px' //设置盒子高度

this.box.style.border = '1px solid #3399ff' //设置边框

this.box.style.borderRadius = '5px' //设置圆的边框

this.box.style.zIndex = '2001' //设置盒子的z轴

this.box.style.backgroundColor = '#FFF' //设置盒子的背景颜色

this.box.style.transform = 'translate(-50%, -50%)' //执行2d动画,把这个盒子位置向反方向移动50%

this.box.innerHTML = '在这里设置盒子的内容,关闭盒子调用实例的hidden()函数即可,如这个实例想这样 loginBox.hidden()//就可以隐藏 '

this.hidden() //隐藏遮罩和盒子

window.onload = (function(o){ //创建匿名函数 参数一 要操作的对象

return function(){ //返回onload事件执行的函数

if(typeof onloadFunc == 'function'){ //判断onloadFunc中有没有函数,防止覆盖其他功能的执行事件

onloadFunc() //执行已经绑定的函数

}

subInit(o) //执行初始化需要执行的函数

}

})(this) //立即执行匿名函数 并传入当前对象

}

this.show = function(){ //显示

this.mask.style.display = 'block'

this.box.style.display = 'block'

}

this.hidden = function(){ //隐藏

this.mask.style.display = 'none'

this.box.style.display = 'none'

}

this.init() //调用初始化函数

}

var loginBox = new popUpBox() //创建一个实例,可以创建N个,互相不干扰

</script>

<body>

<a href="#" onclick="loginBox.show()">弹出盒子</a>

</body>

</html>