繁体   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