[英]How to change img alt src to div strong using javascript
[英]How to refresh offsetHeight of div after changing img src on child using pure javascript?
我需要在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
语句移动了if
它将src
值更改为另一个函数,该函数在上述函数之前被调用。 这解决了上面提到的onclick
问题。 然后,我将左/顶部的div从计算值更改为Joonas89详细介绍的50%
(但在容器div而不是img元素上)以及新的transform属性。 div和img的位置值已经固定,因此不需要更改。
您确定要计算顶部和左侧位置吗? 最好添加一个这样的类,使其始终居中
.parentDiv{
position: relative;
}
.imageElement{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.