打开一个全尺寸未缩放图像的窗口

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 $200 免费信用额度!

对于本网站的图库部分,我希望人们能够查看原始尺寸的屏幕截图。由于本网站的灵活性质,屏幕截图通常会被缩小以适合其列。因此,我将这个解决方案整理在一起。

我的计划是打开一个大小完全适合图像的窗口。在我看来,这很快、简单,而且 UX 完美。您只需执行以下操作

window.open(path-to-image);

实际上,这比这要复杂一些。我们需要传递许多参数来获得我们想要的窗口。主要是,那种 chrome 最少的窗口。顶部有一个关闭按钮,仅此而已。

window.open(path-to-image, null, 'height=y, width=x, toolbar=0, location=0, status=0, scrollbars=0, resizeable=0');

示例

棘手的部分是找出要传递的确切高度和宽度值。您不能只询问图像的大小。您当然可以,但它会说谎。它会告诉你它当前的大小,而不是它自然的大小。

var img = document.getElementById('screenshot');

img.width;  // current size, not natural size
img.height; // current size, not natural size

为了获得自然大小,我们将在 JavaScript 的神奇以太中创建一个新图像,将其源设置为屏幕上图像的源,然后测试其宽度和高度。由于它不受页面上 CSS 的影响,它将正确报告。

var img = document.getElementById('screenshot');
		
var magicEtherImage = new Image();
magicEtherImage.src = img.src;

var padding = 20; // little buffer to prevent forced scrollbars
		
// Values to use when opening window
var winWidth = magicEtherImage.width + padding;
var winHeight = magicEtherImage.height + padding;

我在我的网站上使用 jQuery,所以最终我的代码是这样的

$(".view-full-size").click(function() {

  var mainScreenshot = $("#main-screenshot");
	
  var theImage = new Image();
  theImage.src = mainScreenshot.attr("src");
	
  var winWidth = theImage.width + 20;
  var winHeight = theImage.height + 20;
	
  window.open(this.href,  null, 'height=' + winHeight + ', width=' + winWidth + ', toolbar=0, location=0, status=0, scrollbars=0, resizable=0'); 
	
  return false;
	
});

您可以在单个图库页面上看到它的实际效果 像这样.

显然它在移动设备上不会做太多,所以我只是用媒体查询删除了按钮。