【问题标题】:Compare an image in javascript比较javascript中的图像
【发布时间】:2011-05-07 16:27:22
【问题描述】:

我正在尝试比较 javascript 中的图像。如果图像是真实的,它将更改为不同的图像。我写了一个 if 语句,但它似乎不起作用。有谁知道我如何做到这一点?

function test()
{
imageElement = document.getElementById('pic');
if(imageElement.src == "images/cat_12.gif"){

imageElement.src = "images/press2_12.gif";
}else{

}
}

【问题讨论】:

  • 那么,imageElement.src 包含什么?
  • @Pekka 我认为完全限定的 URL....getAttribute('src') 可以让它工作。

标签: javascript html web


【解决方案1】:
function test(){
    if(imageElement.src.indexOf("images/cat_12.gif") != -1){
       //
    }
}

【讨论】:

    【解决方案2】:

    src 将在您从 Javascript 读取时转换为完整的 URL。您可以尝试提取文件名,例如img.src.substr(img.src.lastIndexOf('/')).

    更好的解决方案是在图像之间使用类和 CSS 背景切换。

    【讨论】:

    • 它似乎不起作用 function test() { img = document.getElementById('pic'); if(img.src.indexOf('images/cat_12.gif')){ imageElement.src = "images/press2_12.gif"; }else{ } }
    • 而且 img.src.substr(img.src.lastIndexOf('/')) 也不起作用,它让所有图像都通过,就好像 if 不适用一样。
    • 请提供其他解决方案
    猜你喜欢
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2015-10-27
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多