簡體   English   中英

屏幕分辨率更改時替換圖像標簽

[英]Replace Image Tag When Screen Resolution Changes

我有一張圖片,像這樣:

<img src="https://preview.ibb.co/drSmLQ/background_full.jpg" />

當頁面大小改變時,我需要用我想要的另一張照片代替!

如何在“ JAVA SCRIPT”中執行此操作?

使用onresize事件,您可以檢測到頁面大小的任何變化,建議您在更改照片之前先驗證一下寬度或高度,如果不執行此驗證,則任何大小上的更改都會改變照片,我認為這不是您想要的。

window.onresize = function(event) {
    if(window.innerWidth < ?){
         document.getElementById("youimageid").src="../newImage.png";
    }
};

如果您想更改視網膜的資產,則可以使用此庫http://imulus.github.io/retinajs/

您還可以在resize事件上添加事件處理程序以獲取寬度,然后在if或switch中求值。

$(window).on('resize', function () {
     // Get the width from body element instead of window.width for cross browser compatibility (Scrollbar)
     var $viewportWidth = $('body').width();
 });

if($viewportWidth > 1200) {
    $('img').attr('src', 'path/to/image.png')
} esle {
    $('img').attr('src', 'path/to/image-2.png')
}

歡迎使用Stack Overflow Arash EB :)

調整browser window大小時,您似乎想切換到另一張圖像。

為此,您需要知道何時更改/調整窗口大小

可能無法預知 ,因為它取決於用戶交互。 用戶可能會決定現在調整大小,或者稍后再調整大小-您不知道,您無法預測何時會發生。

為了解決這個問題,我們發生了一些events

我假設您不完全了解JavaScript events工作方式。 這個想法是給瀏覽器一個指令:

Hey browser, when x happens, run y :

x是事件名稱/您感興趣的動作,

y是您要運行的代碼。 y有時稱為eventHandler/eventListener沒什么,只是一個函數。 -如下所示。 (eventListener與normal code that executes top-to-bottom不同normal code that executes top-to-bottom ,然后可以稍后運行,->當用戶決定執行該操作時。)

在JavaScript中,所有事件都有特定的事件:單擊( click ),調整大小( resize ),移動鼠標( mousemove ),拖動( drag )等-有數百種,並且已經由瀏覽器實現。 在此處查看事件列表

每個事件都與頁面上的對象/元素相關聯。 因此,當您想知道某個特定元素何時執行此操作之一時,您需要register a piece of code to run/eventListener/eventHandler應用於該對象。 當動作/事件發生在該對象上時-您注冊的代碼將運行。 這一切都是自動發生的。

這個事件的想法是JavaScript的核心,在解決這類交互問題時,您需要具備一些高級知識。

在您的特定情況下,您需要將eventListener附加到window object

window是一個像document這樣的global object window包含與當前瀏覽器窗口有關的所有信息。)

let myImage =  document.getElementByTagName('img'); // get a reference to your image, use getElementById if ByTag creates collisions. 


// hey browser! when window is resized (x), run resizeListener (y), get's expressed like this: 

window.addEventListener('resize', resizeListener); // register an eventListener==eventHandler.

function resizeListener (resizeEvent) {
    // resizeEvent is an object containing some data about resizing, is given to you by the browser. 
    // You need to understand *callbacks* to get how resizeEvent ended up in here - but that is for another discussion, and you don't necessarily need it.

   // place some conditional logic in here, to get the behavior you want.
   myImage.src  = "./pathToImage/yourNewImage.jpg";


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM