我正在尝试编写一个照片库页面,其中下面有照片的小图标,当您单击它们时,它们会放大到主照片屏幕。只是我在尝试让 javascript 做我想做的事情时遇到了麻烦。有人可以帮我吗?
到目前为止,这是我的代码:
<?php
$host = "localhost";
$user = "root";
$pwd = "";
$db_name = "gallery";
mysql_connect($host, $user, $pwd)or die("cannot connect");
mysql_select_db($db_name)or die("cannot select DB");
$sql = mysql_query("SELECT * FROM foto ORDER BY id DESC LIMIT 10");
$id = 'id';
$foto = 'foto';
while ($rows = mysql_fetch_assoc($sql))
{
echo "<img class='littleshow'"."id='foto".$rows[$id]."'src='".$rows[$foto]."' onclick='Bigscreen(foto".$rows[$id].")'></img>";
} //the onclick generates onclick="bigscreen(foto1)" and does this again 4 times on the other objects generating foto1,foto2,foto3,foto4
?>
<div id='bigshowcase'></div>
以及到目前为止我的 Javascript:
function Bigscreen () {
var div0 = document.getElementById('bigshowcase');
var images = new array();
images[0] = div0.style.backgroundImage = "url(pic/camera.jpg)";
images[1] = div0.style.backgroundImage = "url(pic/dsc_4255.jpg)";
images[2] = div0.style.backgroundImage = "url(pic/dsc_4373.jpg)";
images[3] = div0.style.backgroundImage = "url(pic/dsc01209.jpg)";
foto1 = images[0]
foto2 = images[1]
foto3 = images[2]
foto4 = images[3]
}
我对 javascript 知之甚少,所以大部分内容可能是错误的。 感谢您的帮助:)
最佳答案
替换这一行:
echo "<img class='littleshow'"."id='foto".$rows[$id]."'src='".$rows[$foto]."' onclick='Bigscreen(foto".$rows[$id].")'></img>";
这样:
echo "<img class='littleshow'"."id='foto".$rows[$id]."'src='".$rows[$foto]."' onclick='Bigscreen(this)'></img>";
并将 Bigscreen
函数更改为:
function Bigscreen(img) {
document.getElementById('bigshowcase').innerHTML ='<img src="' + img.src + '" />';
}
CSS:
<style type="text/css">
#bigshowcase img{max-width:600px;max-height:600px;}
</style>
希望有帮助。
编辑:
请注意,jQuery 总是更好:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$(document).on('click', 'img.littleshow', function(){
$('#bigshowcase').html('<img src="' + $(this).attr('src') + '" />');
});
});
</script>
会完成这项工作。
关于javascript - 一项功能的多次 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19361551/