[英]Move div with fixed position if window size changes
如何執行以下操作:在狹窄的屏幕上打開頁面或更改瀏覽器窗口大小時,我需要一個div來更改它的位置。 當頁面向上或向下滾動時,固定div應該保持在相同的垂直位置,但我還需要它可以說距離最大的div(一個容器用於較小的div,請參見圖片)10px。 現在,當我調整窗口大小時,固定的div會越過右邊的div。
所以問題是如何在垂直滾動頁面時使這個固定的div保持在同一位置並使其始終與正確的div相距10px? 固定的Css類是:
.fixed{
width:40px;
height:40px;
position:fixed;
bottom:100px;
left:100px;
text-indent:-9999px;
}
實際上我正在嘗試實現“返回頂部”按鈕,因此固定div是這個按鈕,最大的div是頁面的內容。
這是我現在擁有的:
改變你的CSS使它看起來像這樣:
.fixed{
width:40px;
height:40px;
position:fixed;
bottom:100px;
left:50%;
margin-left: -[(maincontainerwidth/2) + 50];
text-indent:-9999px;
}
我會采取兩種方式:
1)自定義javascript,讀取窗口的寬度,並更改您的CSS
2)或使用像adapt.js這樣的庫來檢測和交換.css
關鍵術語: 響應式Web設計
看看adapt.js是一個javascript庫,它將根據頁面窗口大小加載不同的css文件。 如果你想在移動和桌面屏幕之間顯示不同的東西,這種技術很棒。
在您的方案中,這也可能起作用。
1)參考adapt.js
<script src="/js/adapt.js" type="text/javascript></script>
2)配置
所以基本上你有兩個觀點:
// Edit to suit your needs.
var ADAPT_CONFIG = {
// Where is your CSS?
path: 'assets/css/',
// false = Only run once, when page first loads.
// true = Change on window resize and page tilt.
dynamic: true,
// Optional callback... myCallback(i, width)
callback: myCallback,
// First range entry is the minimum.
// Last range entry is the maximum.
// Separate ranges by "to" keyword.
range: [
'0px to 760px = Narrow.css', // css for narrow views
'760px to 980px = Narrow.css',
'980px to 1280px = Wide.css', // css for wide views
'1280px to 1600px = Wide.css',
'1600px to 1920px = Wide.css',
'1940px to 2540px = Wide.css',
'2540px = Wide.css'
]
};
3)總之看起來像
<html>
<head>
...
<script src="/js/adapt.js" type="text/javascript></script>
<script type="text/javascript>
// Edit to suit your needs.
var ADAPT_CONFIG = {
// Where is your CSS?
path: 'assets/css/',
// false = Only run once, when page first loads.
// true = Change on window resize and page tilt.
dynamic: true,
// Optional callback... myCallback(i, width)
callback: myCallback,
// First range entry is the minimum.
// Last range entry is the maximum.
// Separate ranges by "to" keyword.
range: [
'0px to 760px = Narrow.css', // css for narrow views
'760px to 980px = Narrow.css',
'980px to 1280px = Wide.css', // css for wide views
'1280px to 1600px = Wide.css',
'1600px to 1920px = Wide.css',
'1940px to 2540px = Wide.css',
'2540px = Wide.css'
]
};
</script>
...
</head>
<body>
...
</body>
</html>
我想控制它的最好方法是使用包裝器div
。 所以,有這樣的事情:
<div class="wrap">
<!-- Contents -->
<div class="fixed">
</div>
</div>
.wrap {width: [fixed width]; position: relative;}
.fixed {left: -100px;}
我覺得包裝div
不是必需的,因為body
本身是relative
position
。 使用此方法, div
保持在相同的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.