position:fixed 总结

发布时间:2023-05-22

一、position:fixed 是什么定位

position:fixed 是CSS中的一种定位方式,与 position:absolute 相似,但是两者有很大的区别。position:fixed 使元素相对于浏览器视口固定位置,即使页面滚动,元素也不会移动。 position:fixed 可以用于创建导航栏、悬浮提示等元素。 下面是一个例子

<style>
#fixed {
 position: fixed;
 right: 0;
 top: 0;
 width: 200px;
 height: 100px;
 background-color: red;
 color: white;
}
</style>
<div id="fixed">
FIXED POSITION
</div>

二、position 什么意思

position 是一个CSS属性,用于确定元素在文档流中的位置。通常也有四种值可以取:staticrelativeabsolutefixed

三、position 属性选取

1. position:fixed 与 z-index

fixed 元素可以运用 z-index 进行层叠顺序的控制,但是请注意 z-index 在子父级元素内的层级关系。下面是一个例子:

<style>
#fixed {
 position: fixed;
 right: 0;
 top: 0;
 width: 200px;
 height: 100px;
 background-color: red;
 color: white;
 z-index: 1;
}
#normal {
 width: 100%;
 height: 1500px;
 background-color: blue;
}
</style>
<div id="fixed">
FIXED POSITION
</div>
<div id="normal"></div>

2. position:fixed 搭配 transform

如果想让 fixed 元素既可以上下拖拽,又可左右移动,可以给元素设置 transform 属性。下面是一个例子:

<style>
#fixed {
 position: fixed;
 right: 0;
 top: 0;
 width: 200px;
 height: 100px;
 background-color: red;
 color: white;
 transform: translate(0, 0);
}
</style>
<script type="text/javascript">
var element = document.getElementById("fixed");
var xStart, yStart, xDrag, yDrag;
element.addEventListener('mousedown', function(event) {
 xStart = element.style.getPropertyValue("transform").split(',')[4];
 yStart = element.style.getPropertyValue("transform").split(',')[5];
 xDrag = event.clientX;
 yDrag = event.clientY;
 element.addEventListener('mousemove', drag)
 element.addEventListener('mouseup', cancelDrag);
});
function drag(event){
 var newPosX = parseInt(xStart) + event.clientX - parseInt(xDrag);
 var newPosY = parseInt(yStart) + event.clientY - parseInt(yDrag);
 element.style.transform = 'translate(' + newPosX + 'px, ' + newPosY + 'px)';
}
function cancelDrag(event){
 element.removeEventListener('mousemove', drag);
 element.removeEventListener('mouseup', cancelDrag);
}
</script>
<div id="fixed">
DRAGGABLE FIXED POSITION
</div>

3. position:fixed 与跨域情况

position:fixed 在跨域情况下会有很多问题。因为 fixed 定位是相对于浏览器视口的,而不是相对于父级元素的。如果跨域,那么 fixed 定位的层级可能会受到限制,导致无法固定在浏览器视口的某个位置上。

4. position:fixed 的兼容性问题

position:fixed 在早期的 IE 所有版本中都不支持,需要使用 JavaScript 进行模拟。而且在 Safari 手机浏览器中,fixed 元素在键盘弹出时有时会失效,需要注意。 在使用 position:fixed 时,需要注意以上几个方面,才能更好地应用于实际开发中。