我實際上試圖讓JS中圖像的方向向它添加一個類。它似乎在Firefox上運行良好,但我在其他瀏覽器上遇到問題。它對於非常小的圖像效果更好,所以如果圖像沒有完全加載,我想這不起作用......但是我找不到解決方案使其正常工作! 謝謝!獲取圖像的方向JS
我的代碼:
$(document).ready(function() {
\t $('.gallery a').find('img').each(function() {
\t \t var imgClass = (this.width/this.height > 1) ? 'landscape' : 'portrait';
\t \t $(this).addClass(imgClass);
\t })
});
.gallery {
\t display: flex;
\t flex-wrap: wrap;
\t width: 450px;
}
.gallery a {
\t width: 200px;
\t height: 200px;
\t display: flex;
\t justify-content: center;
\t overflow: hidden;
}
.gallery a img.landscape {
\t align-self: center;
\t height: 100%;
\t filter: sepia(100%);
}
.gallery a img.portrait {
\t align-self: center;
\t width: 100%;
\t filter: grayscale(100%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gallery">
\t <a href="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
\t \t <img src="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
\t </a>
\t <a href="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
\t \t <img src="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
\t </a>
\t <a href="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
\t \t <img src="http://lorempixel.com/output/city-q-c-1500-1000-3.jpg">
\t </a>
\t <a href="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
\t \t <img src="http://lorempixel.com/output/city-h-c-1000-1500-4.jpg">
\t </a>
</div>
'(this.width> this.height)'代替'(this.width/this.height> 1)'將擺脫潛在DivideByZero問題和少的性能開銷。另外,我相信你必須編寫'$ this.width()'和'$ this.height()'來實現這個功能。 – phil
謝謝Samanime!聽起來像一個好主意,但是當我這樣做時,根本沒有課...... – Julien
確實,改變數學可以修正除數爲零,但它仍然不會給他一個正確的風景或肖像的答案,如果它們沒有加載,它會默認爲一個。既然我們知道它在檢查之前就已經加載了,那麼它的完成方式並不重要。另外,我做了,它應該是'img.width'和'img.height',我錯了。 'Image'元素直接具有寬度和高度,不需要在jQuery中包裝。 – samanime