我需要在div中更改图像,然后通过计算其高度和宽度,然后设置其左侧和顶部值,将其立即在屏幕上居中。但是,当我更改img src并尝试获取div的offsetHeight和clientHeight时,两个值都是错误的。奇怪的是,offsetWidth和clientWidth值是正确的。
有没有一种方法可以刷新div并获取正确的值?
编辑:似乎更改图像src会使之后的所有内容无法正常工作。现在,对onclick事件的更改imageObj.onclick = function() {contractImageView(imageId);};
也不起作用。如果我注释掉if语句,那么所有这些都将再次开始工作。
下面是代码...
// Get the page dimensions
var pageBody = document.getElementById(currentBody);
// If you couldn't get the page body, abort.
if (!pageBody) {
return;
}
var pageBodyHeight = window.innerHeight;
var pageBodyWidth = pageBody.offsetWidth;
var imageDiv = document.getElementById(imageId);
var imageObj = imageDiv.children[0];
var paraObj = imageDiv.children[1];
// If you can't get the div or its image, then abort.
if (!imageDiv || !imageObj) {
return;
}
// Check whether the image has been loaded yet, and load if needed
if (imageObj.src.indexOf('lazy_placeholder.gif') !== -1) {
for (item in photoLazyData) {
if (item === imageDiv.parentElement.id) {
imageObj.src = photoLazyData[item][imageDiv.id];
}
}
}
// Change the images class.
imageDiv.className = 'active_design_div';
imageDiv.style.visibility = 'visible';
imageDiv.style.opacity = 1;
// Set the objects new onclick method to collapse the image
imageObj.onclick = function() {contractImageView(imageId);};
// Calculate the right size
imageDiv.style.maxHeight = pageBodyHeight + 'px';
imageDiv.style.maxWidth = pageBodyWidth + 'px';
imageObj.style.maxHeight = pageBodyHeight + 'px';
imageObj.style.maxWidth = pageBodyWidth + 'px';
// Calculate the margins.
var imageDivWidth = imageDiv.offsetWidth || imageDiv.clientWidth;
// ## THIS IS WRONG IF THE ABOVE IF STATEMENT CHANGES THE SRC ##
var imageDivHeight = imageDiv.offsetHeight || imageDiv.clientHeight;
console.log(imageDiv.offsetHeight + ' : ' + imageDiv.clientHeight);
console.log(imageDiv.offsetWidth + ' : ' + imageDiv.clientWidth);
var leftOffset = (pageBodyWidth - imageDivWidth) / 2;
var topOffset = (pageBodyHeight - imageDivHeight) /2;
// Adjust styling to make the div visible and centred.
imageDiv.style.left = String(leftOffset) + 'px';
imageDiv.style.top = String(topOffset) + 'px';
currentId = imageId;
toggleBlackDiv();
编辑:我最终使用Joonas89的答案进行了这项工作。我基本上将将if
更改src
值的语句移到了另一个函数,该函数在上述函数之前被调用。这样就解决了onclick
上述问题。然后,我将div的左/上从计算值更改50%
为Joonas89所详述的(但在容器div而不是img元素上),以及新的transform属性。div和img的位置值已经固定,因此无需更改。
您确定要计算顶部和左侧位置吗?最好添加一个这样的类,使其始终居中
.parentDiv{
position: relative;
}
.imageElement{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句