在响应式日历图像上,我想要带有日期的文本。当屏幕大小调整到图像将开始调整大小时,该图像上的文本也应该调整大小,以便它相对于图像宽度和高度保持不变。
我通过使用 javascript 实现了这一点,因为我无法仅使用 CSS 来做到这一点。我的问题是,我怎样才能只使用 CSS 来做到这一点?是否可以?如果是,请在我在 fiddle 上创建的代码中显示:
https://jsfiddle.net/bej0od7r/
HTML:
<div class="datePictureHolder">
<img class="img-responsive" alt="News Icon" src="http://shrani.si/f/u/13K/4rB6HshN/news-icon.png"/>
<div class="datePictureText">
<div class="year">2017</div>
<div class="day">25. Feb</div>
</div>
</div>
JavaScript
ResizeDateIcons();
window.onresize = function () {
ResizeDateIcons();
};
function ResizeDateIcons() {
// constants
var imageWidth = 150; // width and height must be the same
var dayTextSize = 36; // text size on maximum image width
var yearTextSize = 23; // text size on maximum image width
var yearLineHeigh = 70;
//
var allImages = document.getElementsByTagName("img");
var allDayTexts = document.getElementsByClassName("day");
var allYearTexts = document.getElementsByClassName("year");
var j = 0;
for (var i = 0; i < allImages.length; i++) {
if (allImages[i].alt === "News Icon") {
allDayTexts[j].style.fontSize = (allImages[i].width / imageWidth) * dayTextSize + "px";
allYearTexts[j].style.fontSize = (allImages[i].width / imageWidth) * yearTextSize + "px";
allYearTexts[j].style.lineHeight = (allImages[i].width / imageWidth) * yearLineHeigh + "px";
j++;
}
}
}
CSS:
.datePictureHolder {
position: relative;
display: inline-block;
}
.datePictureText {
position: absolute;
left: 0;
top: 5%;
width: 100%;
text-align: center;
color: white;
}
.datePictureText .year {
font-size: 23px;
line-height: 70px;
}
.datePictureText .day {
font-size: 36px;
font-weight: bold;
}
.img-responsive {
display: block;
max-width: 100%;
height: auto;
}
最佳答案
抱歉,这有点仓促,但可能会有所帮助!绿色容器仅用于测试目的。
https://codepen.io/anon/pen/gxwZge
.container {
width:20%;
float:left;
background:green;
}
.datePictureHolder {
width:auto;
float:left;
position:relative;
}
.datePictureHolder img {
width:100%;
float:left;
}
.datePictureText {
top:0;
left:0;
position:absolute;
color:white;
width:100%;
text-align:center;
padding:40% 0;
box-sizing:border-box;
font-size:1.2rem;
}
<div class="container">
<div class="datePictureHolder">
<img class="img-responsive" alt="News Icon" src="http://shrani.si/f/u/13K/4rB6HshN/news-icon.png"/>
<div class="datePictureText">
<div class="year">2017</div>
<div class="day">25. Feb</div>
</div>
</div>
</div>
关于javascript - 响应文本大小以及图像上的绝对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45485475/