[英]Enlarging an image to full screen, maintain aspect ratio and then center.
我正在使用jQuery,但是老實說,我不是100%地確定這完全是jQuery問題。
該插件用於畫廊/滑塊,但這可能無關緊要。 我提到它以防有人好奇。
來吧...我有一個圖像,決定高度和寬度,這是需要重置為全屏寬度的寬度。 我想保持寬高比,這樣在調整寬度大小時,圖像的高度變得大於屏幕的高度。 沒關系。 這就是我想要的。 總覆蓋面。 但這里有點凌亂。
我進行了另一次計算,發現多余的高度(img高度-瀏覽器高度)為X。因此,將img的頁邊距設置為:-(X / 2)。 換句話說,圖像將以相等的位垂直居中,現在從頂部和底部被切除。 我希望我有意義。
這在FireFox和IE中可以正常工作,但在Chrome I中,底部會出現一條帶。 如果我將margin-top:bit取出,則黑帶消失,瀏覽器似乎將圖像垂直居中放置。 但這又搞砸了FF和IE。
我想知道我是否誤解了定位,溢出,瀏覽器如何在全屏模式下解釋溢出等更細微的方面。此外,我想提一下,此“滑塊”具有響應能力,因此我可以修復樣式表中的寬度和/或高度。 我一直在使用.attr()來處理我提到的任何一個猴子商業。
另外一件事,有時候我的插件在Chrome中工作得很好,有時會出錯。 例如,我將暫停滑塊,如果沒有單擊開始,它將開始播放。 我應該尋找什么? 這只是我的第二個插件,所以我還是綠色的,可能比我目前的技能水平還抱有更大的抱負:)
如果使用.attr()
,則只能設置/獲取屬性。 如果要更改style
屬性,可以使用.css()
或.attr('style', '<some-style>')
。前者是首選,因為這是它的用途,但后者有效,但它會覆蓋任何其他內聯樣式,而.css()
將允許您只編輯所需的樣式而不影響其他樣式。
Docs:
.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並乘以負數(返回)一個負值,使圖像垂直居中)。
: 0
:最后如果if
語句解析為false
那么返回這個,這會將圖像停靠在它的容器頂部。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.