我试图弄清楚如何在“mainImage”中动态插入边距。我要做的是垂直居中图像,它具有动态高度和宽度(以及动态客户端视口)。我不知道如何在从 javascript 加载图像时将边距添加到图像中......
我有以下 HTML:
<div id="content">
<img id="left" onclick="prevImage('images/52/image_','mainImage',52)" src="icons/arrow_left.png" />
<img id="right" onclick="nextImage('images/52/image_','mainImage',52)" src="icons/arrow_right.png"/>
<img id="mainImage" src="images/52/image_0.jpg" onload="addMargins()" />
</div>
使用以下 CSS:
div#content{
position: absolute;
margin-left: 20%;
margin-right: 5%;
width: 75%;
height: 95%;
text-align: center;
}
div#content img#left{
position: absolute;
left: 0;
top: 50%;
}
div#content img#right{
position: absolute;
right: 0;
top: 50%;
}
div#content img#mainImage{
max-height: 100%;
max-width: 95%;
}
和javascript:
var key = 1;
function nextImage(thePath, id, max)
{
if(key == max)
{
key = 1;
}else{
key++;
}
var image = thePath + key + ".jpg";
document.getElementById(id).src= image;
};
function prevImage(thePath, id, max)
{
if(key == 1)
{
key = max;
}else{
key--;
}
var image = thePath + key + ".jpg";
document.getElementById(id).src= image;
};
所以我的想法是在javascript中做一些基本上说的事情:
"var viewport= viewport.height;
var mainImage= mainImage.height;
set marginTop to (viewport-mainImage)/2;
set marginBottom to (viewport-mainImage/2;"
并在每个图像通过“下一个/上一个”按钮加载时执行此操作。