【问题标题】:Change image in html keeping size javascript更改 html 中的图像保持大小 javascript
【发布时间】:2014-01-21 10:08:04
【问题描述】:

我在更改 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;
    }


}

我希望所有图像都具有与第一个图像相同的方面,我的意思是,相同的高度和宽度。有可能吗?

我被要求用 photoswipe 来做,但我觉得有点困难,所以我想不时做这个,下周仔细阅读所有关于 photoswipe 的内容。

编辑:我将 class="cropTest" 更改为 div 而不是图像,现在所有图像都已“调整大小”。我使用“”是因为它们更小。 img 标签会适应图像,但我不希望发生这种情况。我想要一个不同的图像,但保持大小。我不介意图像看起来模糊或像素化。

【问题讨论】:

  • id EJ_test 的元素是否设置了任何宽度属性?
  • 不,我还没有为它创建css。

标签: javascript image crop


【解决方案1】:

您可以使用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;
        }
    }

【讨论】:

    猜你喜欢
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2010-11-13
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多