我的计划如下:
创建一个简单的静态网站,其中包含一些基于浏览器宽度加载的图片(因为移动用户不需要加载大图片)。
我尝试了我在那里找到的建议:
I'm unable to center an image inside a div after being loaded with jquery
但它似乎不适合我。我尝试了那里的答案,但没有帮助。
我甚至试过这种事后更改属性:用jQuery加载的中心HTML元素
$('.headerImg').css('margin','auto');
和几个在太链接的想法。但似乎忽略了中心定位。用于测试目的的图像根据屏幕的宽度正确显示,并且在我的css文件中没有多个定义。如果有人有线索,我会真正体会到它...
我的代码:
<html>
<head>
<title>broken</title>
<!--styling-->
<link rel="stylesheet" type="/styling/" href="styles.css">
</head>
<body>
<!-- Scripts-->
<script src="scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="scripts/constants.js"></script>
<!-- fetch and store screen sizes-->
<script type="text/javascript">
localStorage.setItem("windowWith", screen.width);
localStorage.setItem("windowHeight", screen.height);
localStorage.setItem("imageSize", getImageSize());
</script>
<!--Header-->
<div class="header">
<script type="text/javascript">
var path = "media/img/header_" + localStorage.getItem("imageSize") + ".jpg";
$(document).ready(function() {
$('.headerImg').attr("src", path);
});
</script>
<img class="headerImg"></img>
<br>
<div class)"menuItems"></div>
</div>
<!--Middle-->
<div class="middle"></div>
<!--Footer-->
<div class="footer"></div>
</body>
</html>
这里是计算所需要的* .js文件,其画面选择的是:
//const enum to define where
var width = {
large:1280,
medium:800,
small:460,
xsmall:330
};
//sets the size for the header image
function getImageSize(){
var size = "";
var screenWidth = localStorage.getItem("windowWith");
if(screenWidth > width.medium){
console.log("loading large picture");
size = "large";
}
else if(screenWidth <= width.medium && screenWidth > width.small){
console.log("loading medium picture");
size = "medium";
}
else if(screenWidth <= width.small && screenWidth > width.xsmall){
console.log("loading small picture");
size = "small";
}
else if(screenWidth < width.small){
console.log("loading xsmall picture");
size = "xsmall";
}
if(size == ""){
size = "xsmall";
console.log("Error - screen size not found - loading xsmall header");
}
return size;
}
要水平居中然后'显示:inline-block的; margin:0 auto;'为你的图像,'text-align:center;'为父母应该做的工作。你试过了吗?并且在'
'你的html语法中有一个错误,我希望你已经注意到 –这里有一个[link](https://css-tricks.com/responsive-images-youre-just-changing-resolutions-use -srcset /),它不能解决你的问题,但它比使用jQuery在不同的宽度动态设置不同的图像更好的方法: –
感谢指出错误 - 但风格并没有解决它。 (链接)问题中也提到了它们。我也许应该提及我总是在没有缓存的情况下查看网站。 @ValentinoPereira:它看起来很酷,但它不被M $:Edge和IE支持......所以我必须使用另一种方法。 – Garamaru