我正在尝试使用下面的代码
在点击图片时实现Lighbox效果 document.addEventListener('click',function(){
var target = event.target || event.srcElement;
if(target.className == "acv"){
var id = target.id, src= target.src,
type = target.nodeName, imgW, imgH,
temp = document.createElement('div'),
sHeight = screen.availHeight,
sWidth = screen.availWidth,
st = temp.style;
var img = new Image();
img.onload = function(){
imgW = this.width;
imgH = this.height;
}
img.src = src;
var imgH = ( sHeight >= imgH + 20 ? imgH : (sHeight - 20) );
var imgW = ( sWidth >= imgW + 20 ? imgW : (sWidth - 20) );
img.style.height = imgH;
img.style.width = imgW;
img.style.position = "relative";
img.style.left = ( (sWidth - imgW) / 2 ) + "px";
img.style.top = ( (sHeight - imgH) / 2 ) + "px";
temp.appendChild(img);
temp.id = "lightbox";
st.width = sWidth + "px";
st.height = sHeight + "px";
st.backgroundColor = "Gray";
st.zIndex = 123;
st.position = "absolute";
st.top = st.left = 0;
st.margin = "0 auto";
document.body.appendChild(temp);
}
});
请检查工作小提琴here。
我觉得我在这方面做错了什么。请更正并帮助我改进代码。
答案 0 :(得分:1)
document.addEventListener('click', function() {
var target = event.target || event.srcElement;
if (target.className == "acv") {
// debugger;
var id = target.id,
src = target.src,
type = target.nodeName,
imgW, imgH, temp = document.createElement('div'),
sHeight = screen.availHeight,
sWidth = screen.availWidth,
st = temp.style;
var img = new Image();
img.src = src + '?rand=' + Math.random();
//HIDE before we sure that image loaded!
img.style.display = "none";
var pos_img = function(img) {
var imgH = img.height,
imgW = img.width;
imgH = (sHeight >= imgH + 20 ? imgH : (sHeight - 20));
imgW = (sWidth >= imgW + 20 ? imgW : (sWidth - 20));
img.style.height = imgH;
img.style.width = imgW;
img.style.position = "relative";
img.style.left = ((sWidth - imgW) / 2) + "px";
img.style.top = ((sHeight - imgH) / 2) + "px";
//SHOW IMAGE BACK
img.style.display = "block";
};
//image not loaded?
if (img.complete === false) {
img.addEventListener('load', function(e) {
console.log("LOAD", e, img);
//TODO remove EventListener ?
pos_img(img);
});
} else {
pos_img(img);
}
temp.appendChild(img);
temp.id = "lightbox";
st.width = sWidth + "px";
st.height = sHeight + "px";
st.backgroundColor = "Gray";
st.zIndex = 123;
st.position = "absolute";
st.top = st.left = 0;
st.margin = "0 auto";
document.body.appendChild(temp);
}
});
我也会使用 window 宽度/高度来计算位置。
请注意,上面的代码没有给你生产代码,只是为了显示逻辑错误在哪里。 如果尝试点击jslint按钮,你可能不会问这个问题