我的计划如下:
使用一些图片创建一个简单的静态网站,这些图片基于浏览器宽度加载(因为移动用户不需要加载大量图片)。
我尝试了在那里找到的建议:
I'm unable to center an image inside a div after being loaded with jquery
但它似乎不适合我。我尝试了那里的答案,但没有帮助。
之后我什至尝试更改属性:
$('.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;
}
最佳答案
图片标签是行内元素,不能用"margin: 0 auto;"居中
使图像“显示: block ;”
你的 css 应该是这样的:
.headerImg {
display: block;
margin: 0 auto;
}
关于javascript - 使用 jQuery 加载的居中 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44617860/