[英]jQuery/CSS: Changing the height and width attributes of an image when clicked
我正在使用HTML,CSS和jQuery构建一个简单的库。 用户单击图像时,应在框架中弹出一个较大版本的图像,并在其后面覆盖一个叠加层。 对于水平方向的图像我没有问题,但是对于垂直方向的图像,较大的图像失真了。
您可以在CodePen上查看我的工作示例: http ://codepen.io/anfperez/pen/AXZgRV
我尝试通过将图像的高度保存在变量中并使用jQuery更改属性来更改图像的属性,但是它似乎不起作用。
如何访问较大图像URL的高度和宽度并放入框架中? 我正在尝试以下代码,该代码不起作用。
var height_large = $(this).attr('height')
var width_large = $(this).attr('width')
$('#frame img').attr('height', height_large)
$('#frame img').attr('width', width_large)
供参考,这是我要下拉的照片的实际URL: https : //farm8.staticflickr.com/7072/7274940170_c166072ddf_c.jpg
将#frame img的高度更改为auto对我有用。 它以固定的宽度显示较大的图像,并相应地调整高度。 因此,它使它成比例地正确。 您只需要确保图像的宽度至少与固定宽度相同就可以避免放大。
#frame img {
display: none;
position: fixed;
background-color: white;
width: 700px;
height: auto;
margin-left: -350px;
left: 50%;
}
在框架中设置src
并在CSS的width
和height
设置这些值之后,即可读取图像的naturalWidth
和naturalHeight
属性。 您应该为帧图像设置load
事件侦听器,以便在交换新src
时在图像完成加载后立即对其进行设置,并通过将marginLeft
调整为新图像宽度的一半来重新居中图像。 您还可以将帧/叠加层的淡入淡出效果移入此效果,以便在单击时淡入为正确的大小,而不是在淡入时自行调整:
$('#frame img').on('load', function(e) {
e.target.style.width = e.target.naturalWidth + 'px';
e.target.style.height = e.target.naturalHeight + 'px';
e.target.style.marginLeft = -(e.target.naturalWidth / 2) + 'px'; //re-center the image
$(this).fadeIn();
$('#overlay').fadeIn();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.