一、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屬性,用於確定元素在文檔流中的位置。通常也有四種值可以取:static、relative、absolute、fixed。
三、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 時,需要注意以上幾個方面,才能更好地應用於實際開發中。
原創文章,作者:ZFHCF,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/333071.html
微信掃一掃
支付寶掃一掃