我正在开发一个 PHP 项目,在该项目中我试图在鼠标悬停后显示图像预览。我正在尝试使用 JS 脚本,但它没有按预期工作。我必须根据文件名在 for 循环中传递图像 URL。我总是看到预览。
代码:
<!doctype html>
<html lang="en">
<head>
<style>
.test {
display: none;
}
.underline {
text-decoration: underline;
}
</style>
</head>
<body>
<?php
echo "
<table align='center' class='loopblock'>
<tr class='loop'>
<td>Template ID Client: $client_id </th>
</tr>
";
echo "<table align='center' class='loopblock'>";
$path = "/var/www/html/pdf/";
$files = scandir($path);
$files = array_diff(scandir($path), array('.', '..'));
$counter = 1;
foreach($files as $key) {
echo "
<tr class='label-loop'>
<td class='counter' align='left' width='100' >
<a class='label-loop' align='left' href='/send-email.php?fileName=$key'>
$counter
</a>
</td>
<img id='test' src='PATH/to/image.png'>
Name
</img>
<td class='click' align='center' width='500' class='loop'>
<a class='loop' align='right' href='/send-email.php?fileName=$key'>
$key
</a>
</td>
</tr>
";
$counter++;
}
echo"</table>";
?>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script>
$(document).ready(function () {
$('span').hover(function(){
$(this).addClass('underline'); //to make text underlined on hover
$('#image').show(); //displays image on mouse in
},function(){
$(this).removeClass('underline'); //remove underline on mouse out
$('#image').hide(); //hides image on mouse out
});
});
</script>
</body>
</html>
最佳答案
以下 css 代码设置 class test
的显示,但只有一个 id test
在这里<img id='test' src='PATH/to/image.png'>Name</img>
:
.test{
display: none;
}
由于图像是在循环中创建的,因此它应该是一个类而不是 ID。
还有你的Javascript代码$('#image').hide();
用于id image
,在您的代码中找不到它。
因此,要么您的问题中缺少一些代码,要么以上可能是您的问题。
编辑:
您的悬停也会由 span
触发标签,无处可寻。如果您更改了 test
对于一个类,你必须使用 $('.test').show();
编辑2:
这是一个 js 示例,说明如何使用 td 悬停并仅显示其中的图像:
HTML/PHP 部分:
foreach($files as $key) {
echo "
<tr class='label-loop'>
<td class='counter' align='left' width='100' >
<a class='label-loop' align='left' href='/send-email.php?fileName=$key'>
$counter
</a>
</td>
<td class='click loop' align='center' width='500'>
<a class='loop' align='right' href='/send-email.php?fileName=$key'>
$key
</a>
<img class='test' src='PATH/to/image.png'>
</td>
</tr>
";
$counter++;
}
JS 部分:
$(document).ready(function () {
$('td.click').hover(function(){
$(this).addClass('underline'); //to make text underlined on hover
$(this).find(".test").show(); //displays image on mouse in
},function(){
$(this).removeClass('underline'); //remove underline on mouse out
$(this).find(".test").hide(); //hides image on mouse out
});
});
关于javascript - PHP、JS : Preview with mouse hover not working, 默认情况下始终显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54765568/