将图像放大到全屏,保持纵横比然后居中。
我正在使用jQuery,但老实说,我并非100%确定这完全是一个jQuery问题。
该插件适用于图库/滑块,但这也许无关紧要。 我提到它以防有人好奇。
这里…我有一个图像并决定高度和宽度,它是需要重置为全屏宽度的宽度。 我想保持宽高比,这样在调整宽度大小时,图像的高度会变得大于屏幕的高度。 没关系。 这就是我想要的。 总覆盖面。 但这里有点凌乱。
我做了另一个计算,并发现多余的高度(img height – broswer height)是X.所以我设置了img的margin-top: – (X / 2)。 换句话说,图像将垂直居中,相同的位现在从顶部和底部切断。 我希望我有意义。
这在FireFox和IE中运行良好,但在Chrome中,我最终在底部有一个乐队。 如果我将margin-top:bit取出,那么黑带就会消失,浏览器似乎会自动垂直居中。 但后来搞砸了FF和IE。
我想知道我是否误解了一些更微妙的定位,溢出,浏览器如何解释全屏溢出等等。另外,我想提一下,这个“滑块”是响应所以我可以修复样式表中的宽度和/或高度。 我一直在使用.attr()来处理我提到的任何一个猴子商业。
另外一件事,有时候我的插件在Chrome中工作得很好,有时会出错。 例如,我将暂停滑块,它将在没有单击开始的情况下开始播放。 我应该寻找什么? 这只是我的第二个插件,所以我仍然是绿色的,可能比我目前的技能水平更雄心勃勃:)
如果使用.attr()
,则只能设置/获取属性。 如果你想改变style
属性,你可以使用.css()
或.attr('style', '
。前者是首选,因为这是它的用途,但后者有效,但它会覆盖任何其他内联样式,而.css()
将允许您只编辑所需的样式而不影响其他样式。
文件:
-
.attr()
: http : //api.jquery.com/attr -
.css()
: http : //api.jquery.com/css
这是我提出的:
//cache the image we want to manipulate var $img = $('img'); //bind an event handler to the `resize` event for the viewport $(window).on('resize', function () { //get the width and height of the viewport and store it in an object, //also get the aspect ratio of the image and it's calculated height based on the viewport's width var viewport = { width : $(this).width(), height : $(this).height() }, ratio = ($img.height() / $img.width()), imgHeight = Math.floor(viewport.width * ratio); //update the CSS of the image element $img.css({ width : viewport.width, height : imgHeight, marginTop : (imgHeight > viewport.height) ? Math.floor((imgHeight - viewport.height) / 2 * -1) : 0 }); //trigger a `resize` event to fire on the `window` object for page-load so the element is loaded as full-width }).trigger('resize');
这是一个演示: http : //jsfiddle.net/Zex4S/1/
请注意.on()
是jQuery 1.7中的新增内容,在这种情况下与.bind()
相同: http : //api.jquery.com/on
(imgHeight > viewport.height) ? Math.floor((imgHeight - viewport.height) / 2 * -1) : 0
(imgHeight > viewport.height) ? Math.floor((imgHeight - viewport.height) / 2 * -1) : 0
:这是一段重要的代码,它是一个三元运算。
(imgHeight > viewport.height)
:这是if语句的开头,检查imgHeight
值是否大于viewport.height
值。
? Math.floor((imgHeight - viewport.height) / 2 * -1)
? Math.floor((imgHeight - viewport.height) / 2 * -1)
:如果语句解析为true
那么这将是返回的内容, imgHeight
减去viewport.height
除以2并乘以负数1(返回)一个负值,使图像垂直居中)。
: 0
:最后如果if
语句解析为false
那么返回这个,这将图像停靠在它的容器顶部。