我正在开发一个项目,尝试在所有浏览器尺寸的图像上的一行上方添加文本。当您看到下面的 codpen 链接时,这一点会更清楚。
我现在面临的问题是,一旦我将顶部值设置到正确的位置并更改浏览器宽度,文本就不再位于该行上方。
#text{
position: absolute;
top: 685px;
}
html,body {
margin:0;
padding:0;
}
#background_pic
{
width: 100%;
}
<image src="https://vignette.wikia.nocookie.net/uncyclopedia/images/4/47/Horiz-line.JPG/revision/latest/scale-to-width-down/600?cb=20050929041542" id="background_pic"></image>
<div id="text">
hello world
</div>
您设置了#text
从顶部到静态位置,这不适用于所有屏幕尺寸(可能会有所不同),这将导致图像发生变化。
您想要根据图像高度动态设置文本。下面是一个使用 JavaScript 的示例:
function setTextPosition() {
// get html elements
var image = document.querySelector('#background_pic');
var text = document.querySelector('#text');
// get height of image
var imageHeight = image.clientHeight;
// dynamically set text position (the '-20' is meant to make the text stay above the line)
text.style.top = imageHeight/2 - 20 + 'px';
}
// set the text position on load and resize
window.addEventListener('load', setTextPosition);
window.addEventListener('resize', setTextPosition);
#text{
position: absolute;
top: 685px;
}
html,body {
margin:0;
padding:0;
}
#background_pic
{
width: 100%;
}
<image src="https://vignette.wikia.nocookie.net/uncyclopedia/images/4/47/Horiz-line.JPG/revision/latest/scale-to-width-down/600?cb=20050929041542" id="background_pic"></image>
<div id="text">
hello world
</div>
尝试上面的代码片段,看看调整它的大小如何始终允许文本保持在该行的正上方。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)