我目前正在一个网站上工作,我使用具有背景图片的div
,以便即使在iOS上也能保持fixed
属性。代码如下:
HTML:
<div id="background" style="background-image: url(bi.jpg);"></div>
CSS:
#background{
position:fixed;
height: 100%;
width: 100%;
z-index:-1;
display:block;
background:no-repeat 50% 0%;
background-size:cover;
}
这适用于大多数视口大小,但在iOS Safari浏览器中,当用户向下滚动时,顶部的工具栏会缩小。这会更改视口高度,cover
属性会尝试补偿此值,因此在滚动完成后它会捕捉到稍微新的大小。有没有办法确保背景图像覆盖整个屏幕并且在滚动后不会改变?这可能需要一些JS,但我不确定。谢谢。
答案 0 :(得分:0)
I found a solution to this problem by making a script that runs when the browser is an iOS safari. It gets the height of the screen and sets the background to that height making it so when the viewport resizes on scroll the whole image doesn't resize but rather continues.
function checkSafari(){
"use strict";
var height = $(window).height();
var heightAdd = height + 40; // add __ px to background height
var heightAddMore = heightAdd + 30; // add more for case iphone
var userAgent = window.navigator.userAgent;
if (userAgent.match(/iPad/i)) {
$("#background").css({"background-size":"auto " + heightAdd +"px"});
}
else if(userAgent.match(/iPhone/i)) {
$("#background").css({"background-size":"auto " + heightAddMore +"px"});
}
}
But this would make the background an incorrect size when the user changes the orientation so I made another function to rerun this function on orientation change.
function detectOrientation(){
"use strict";
var userAgent = window.navigator.userAgent;
if(userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)){
$(window).on("orientationchange", function(event){
checkSafari();
});
}
}