如果您要使用纯JavaScript,则可以设置onclick事件侦听器并获取图像的实际大小(确定图像在浏览器中的原始大小吗?),然后将此大小设置为image。(如果您希望第二次单击将其设置为旧尺寸,请将旧尺寸保存到全局变量中,然后进行设置)。看起来像这样:
我对纯JavaScript不太满意,但我想是这样。
将此代码添加到文件中的某个位置。它将为每个图像运行
window.onload = function() {
images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++){
images[i].onclick = function(e){
var isBig = e.target.getAttribute('isBig');
if (isBig === undefined || isBig == 'false'){
// make it big
e.target.setAttribute('isBig', 'true');
e.target.setAttribute('oldWidth', e.target.offsetWidth);
e.target.setAttribute('oldHeight', e.target.offsetWidth);
var newImg = new Image();
newImg.onload = function() {
e.target.style.width = newImg.width+"px";
e.target.style.height = newImg.height+"px";
}
newImg.src = e.target.getAttribute('src');
}
else {
// make it small
e.target.setAttribute('isBig', 'false');
e.target.style.width = e.target.getAttribute('oldWidth')+"px";
e.target.style.height = e.target.getAttribute('oldHeight')+"px";
}
}
}
}
这会将图像的宽度和高度设置为原始大小。
如果要使用绝对定位使其全屏显示,则需要创建一个新元素和img标签。您只需要将其src设置为图像的src。然后,您可以显示该图像。例子:
X
function closeImage() {
document.getElementById("bigImage").style.visibility = 'hidden';
}
images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++){
// on image click
images[i].onclick = function(e){
// set image src
document.getElementById("bigImageChild").src = e.target.src;
// show image
document.getElementById("bigImage").style.visibility = 'visible';
}
}