我正在设计一个在服务器上显示任何歌曲图标的站点。我创建了一个php文件,该文件返回歌曲的图像(如果存在)。我的HTML代码:
<img src="/image.php?song=SongName" width="100" height="100">
如果给定的歌曲具有封面图标,则img元素将显示该图标。如果没有,我会得到一个空的100x100 img框。
现在,我想在javascript中指定URL地址:'/image.php?song=SongName'是否返回null(如果歌曲上没有图像封面),以便隐藏img。如何实现呢?
谢谢。
PS。到目前为止,我已经尝试过的代码(用于img url的格式有一些php):
var picElement = document.getElementById("picture");
picElement.src = "/image.php?song=$nameFile";
if(picElement.src == null){
picElement.style.display = "none";
}else if(picElement.src !=null){
picElement.src = "/image.php?song=$nameFile";
picElement.style.height = "20vh";
picElement.style.width = "20vh";
picElement.style["boxShadow"] = "3px 3px 10px 1px #e2b674";
}
image.php下的php代码:
<?PHP
$song= $_GET["song"];
require_once("getID3-1.9.15/getid3/getid3.php");
$Path= .$song.".mp3";
$getID3 = new getID3;
$OldThisFileInfo = $getID3->analyze($Path);
if(isset($OldThisFileInfo['comments']['picture'][0]))
{
header('Content-Type: ' . $OldThisFileInfo['comments']['picture'][0]['image_mime']);
echo $OldThisFileInfo['comments']['picture'][0]['data'];
die;
}?>
最佳答案
如果要仅使用标记来显示默认图像,则可以为每个图像添加 onerror="this.src='/image.php?song=Default'"
或类似属性:
<img src="/image.php?song=SongName" onerror="this.src='/image.php?song=Default'" width="100" height="100"/>
假设找不到图像时
/image.php
将正确返回404错误,而不是显示默认图像本身。更新资料
按照您的PHP代码,您可能只想将歌曲名称回显为HTML而不是JavaScript:
<img src="/image.php?song=<?PHP echo $nameFile; ?>" onerror="this.style.display='none'" width="100" height="100" />
关于javascript - 指定url图片是否为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50221011/