簡體   English   中英

在html中更改圖像以保持大小javascript

[英]Change image in html keeping size javascript

我在更改html的img標簽中的圖像時正在嘗試一個問題。

我在fiddle中做了一個示例,該示例可作為我在互聯網上找到的圖像的網頁使用,因此它們不相等: http : //jsfiddle.net/kZp7V/

這是腳本代碼:

    var counterImage = 0;
    var ccI = new Array('http://tiendas.fnac.es/la-canada/files/2010/12/Peque%C3%B1a-orquesta-mediterr%C3%A1neo-300x286.jpg',
                        'http://muack.es/wp-content/uploads/2013/04/smalldata1.jpg',
                        'https://pbs.twimg.com/profile_images/604644048/sign051.gif'
                        );
window.image = function(element){
    if(counterImage < 3){
        document.getElementById("EJ_test").setAttribute('src', ccI[counterImage]);
        counterImage++;
    }
    else{
        document.getElementById("EJ_test").setAttribute('src', ccI[0]);
        counterImage = 1;
    }


}

我希望所有圖像都具有與第一個相同的外觀,我的意思是,相同的高度和寬度。 有可能嗎?

我被要求用光擦進行此操作,但是我發現它有點困難,因此我不時要這樣做,然后仔細閱讀下周有關光擦的所有內容。

編輯:我將class =“ cropTest”更改為div而不是圖像,現在所有圖像均已“調整大小”。 我使用“”是因為它們較小。 img標簽會適應圖像,但我不希望發生這種情況。 我想要一個不同的圖像,但要保持大小。 我不介意圖像看起來模糊或像素化。

您可以使用getComputedStyle獲取圖像的當前大小,並使用該信息一次,例如,通過檢查寬度樣式是否已由您設置。 例:

   window.image = function(element){
        if (!document.getElementById("EJ_test").style.width) {
            var currentStyle = window.getComputedStyle(document.getElementById("EJ_test"));
            document.getElementById("EJ_test").style.width = 
                currentStyle.width;
            document.getElementById("EJ_test").style.height = 
                currentStyle.height;
        } 
        if(counterImage < 3){
            document.getElementById("EJ_test").setAttribute('src', ccI[counterImage]);
            counterImage++;
        }
        else{
            document.getElementById("EJ_test").setAttribute('src', ccI[0]);
            counterImage = 1;
        }
    }

暫無
暫無

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

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