根據瀏覽器尺寸的不同,我在換取圖片時遇到了一些困難。如何更改窗口大小的img src?
我在瀏覽器調整大小時需要在頁面上收集圖像集合。我已經基本上將我的所有圖像分成了子文件夾,具體寬度。即。我有一個名爲'1280','1152','1024'等的文件夾。當瀏覽器被重新調整大小並且命中正確的斷點時,我使用javascript來查找並替換文件夾名稱。
就目前來看,我有的代碼確實是的工作,但只有當頁面重新加載時。如果用戶保持鼠標不動並調整窗口大小,路徑不會改變,或者看起來它們在第一個斷點被命中後不會改變。從寬度> 1280px到低於1152px。
問題是我已經花了整整一天的時間編碼,而且我只能在今天結束的時候進入這個環節..所以我的思想已經完全模糊了,我無法從邏輯上思考這個問題!如果任何人都可以在這裏幫助我,我將不勝感激,因爲我有一個緊迫的期限,我需要完成。
我已經下調了代碼,使其更清晰,但是這是我到目前爲止有:
<img src="/images/1280/img1.jpg" alt="" class="swap" />
<img src="/images/1280/img2.jpg" alt="" class="swap" />
<img src="/images/1280/img3.jpg" alt="" class="swap" />
<img src="/images/1280/img4.jpg" alt="" class="swap" />
<img src="/images/1280/img5.jpg" alt="" class="swap" />
和JavaScript:
function checkResolution() {
// Resolution width > 1280px
if ($(window).innerWidth() > 1280) {
replaceImagePaths("1280");
}
// Resolution 1152px - 1279px
else if ($(window).innerWidth() >= 1152 && $(window).innerWidth() <= 1279) {
replaceImagePaths("1152");
}
// Resolution width 1024px - 1151px
else if ($(window).innerWidth() >= 1024 && $(window).innerWidth() <= 1151) {
replaceImagePaths("1024");
}
// Resolution width 768px - 1023px
else if ($(window).innerWidth() >= 768 && $(window).innerWidth() <= 1023) {
replaceImagePaths("768");
}
// Resolution width < 768px
else if ($(window).innerWidth() <= 767) {
replaceImagePaths("mobile");
}
}
$(window).resize(function() {
checkResolution();
});
$(document).ready(function() {
checkResolution();
});
function replaceImagePaths(resolution) {
// Switch images
$('.swap').each(function() {
var imagePath = $(this).attr('src');
$(this).attr('src', imagePath.replace("mobile", resolution));
$(this).attr('src', imagePath.replace("768", resolution));
$(this).attr('src', imagePath.replace("1024", resolution));
$(this).attr('src', imagePath.replace("1152", resolution));
$(this).attr('src', imagePath.replace("1280", resolution));
}
}
似乎什麼奇怪的是,假設你開始從大於1280的瀏覽器寬度並調整大小,路徑將切換爲下一次測量,即。從1280年到1152年,但之後似乎並不奏效。他們做然而,所有的工作,當頁面刷新後,重新調整大小。
我知道它與我的replaceImagePaths()函數有關,但我無法弄清楚我要出錯的地方。該功能背後的理論是,我只是毛毯取代每一個路徑,但它似乎好像我覆蓋的價值..我不知道。那裏肯定會有古怪的事情發生。
感謝您的幫助!
(PS我知道有切換出根據瀏覽器的大小,但在這種特殊情況下的圖像許多可供選擇的方法,我用JS這樣做)
謝謝戴爾。我實際上已經關閉了我的循環......這只是我從複製/粘貼的錯字:-)。無論如何,我只是快速看看它似乎你的功能正在工作!非常感謝。我明天在辦公室時必須進行更徹底的測試,但似乎你已經解決了這個問題 - 你已經救了我的一天! – alimac83
不客氣,很高興我能幫到你! – UpHelix
這個答案絕對應該有更多的票!非常感謝,男人! – Garavani