css实现标签固定悬浮在某个位置(position:fixed)

您所在的位置:网站首页 html向下浮动属性 css实现标签固定悬浮在某个位置(position:fixed)

css实现标签固定悬浮在某个位置(position:fixed)

2023-07-28 00:56| 来源: 网络整理| 查看: 265

关键用到的就是固定定位(position:fixed)和层叠属性(z-index)

.fix-box{ text-align: center; top:35px; position:fixed; z-index:100; }

知识点详细解析 position:fixed:

盒子将脱离原来的文本流,进入到新的一层

会盖在原来文本流之上,并且可以通过left right top bottom 四个属性,对盒子进行移动,移动的基准是浏相对于览器视窗,与其他盒子无关

盒子固定定位后,回脱离原来的文本,同样将不在具有原来的特性,宽高由内容撑开,margin:会叠加; 一般不用margin进行位置改变任何盒子都可以fixed

代码形式如下:

position:fixed;//设置位置属性; left/right/top/bottom/right:10px;//进行定位操作; z-index:100;//设置该盒子的显示优先级;没有单位 0开始增大 值越大越开始靠前;

案例如下: 在js里通过获取id为need-fixed的div,然后获取scrollTop属性判断距离顶部的位置大于某个值时,调用悬浮固定的定位样式,总之就是在需要悬浮固定显示div的时候才让它进行显示

html:

页面内容

css:

.fixed-box { background-color: #d3d3d3; width: 80%; position: fixed; top: 0; z-index: 9999; }

js:

window.onload = function () { var need-fixed = document.getElementById('need-fixed'); window.onscroll = function () { var top = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop//w3c,各ie的兼容 if (top >= 50) { addClass(need-fixed, 'fixed-box'); } else { removeClass(need-fixed, 'fixed-box'); } } } function addClass(ele, classname) { var oldClass = ele.className; var pattern = new RegExp('(^|\\s)' + classname + '(\\s|$)'); if (!pattern.test(oldClass)) { ele.className += ' ' + classname; } } function removeClass(ele, classname) { var oldClass = ele.className; var pattern = new RegExp('(^|\\s)' + classname + '(\\s|$)'); if (pattern.test(oldClass)) { ele.className = ele.className.replace(pattern, ' '); } }

scrollTop:元素滚动条被向下拉动的距离。返回值是一个整数,单位是像素



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3