javascript - 一项功能的多次 onclick

标签 javascript php css

我正在尝试编写一个照片库页面,其中下面有照片的小图标,当您单击它们时,它们会放大到主照片屏幕。只是我在尝试让 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/

相关文章:

CSS Opacity 不显示在 Chrome 中,而是显示在 JSFiddle 中

css - 如何在 CSS 中使用原生浏览器大纲?

html - CSS - 为什么这个不可见的边距被应用到我的 <a> 标签 css-button?

javascript - 将过滤后的数据从 php 保存到 Excel

javascript - 使用 easeljs/canvas/javascript 围绕它的中心旋转图像,同时图像保持在起始位置

javascript - jQuery - 有什么区别

php - PDO 在重复 key 更新时插入

php - Yii2:多个事件附加在 View 上

javascript - jquery/js onload停止播放iframe视频

php - 如果php输入变量为空,如何保持数据库表数据不被修改?