点击照片更改

时间:2013-07-15 15:45:38

标签: javascript jquery html javascript-events

我想创建一个功能,我可以从一些照片中选择,如果我点击一个,它应该在大框架中也会改变,也会显示(照片)。

我想我可能搞砸了选择者。

HTML

<div id="photo">
    <img src="http://hd.highresolution-wallpapers.net/wallpapers/space_dimesional_sun-600x800.jpg" alt="Space" />
</div>
<div id="gallery">
    <ul>
        <li class="selected"><a href="http://hd.highresolution-wallpapers.net/wallpapers/space_dimesional_sun-600x800.jpg"><img src="http://hd.highresolution-wallpapers.net/wallpapers/space_dimesional_sun-600x800.jpg" alt="Space" /></a>
        </li>
        <li><a href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSh_AgoWSwWBYuvqlbD7kzIrtcPRCV3jGzn5H4fosJRba8JzE1-Ow"><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSh_AgoWSwWBYuvqlbD7kzIrtcPRCV3jGzn5H4fosJRba8JzE1-Ow" alt="Grass" /></a>
        </li>
        <li><a href="http://sitch.org/sailing/images/2006-11-17__sun__600_800.jpg"><img src="http://sitch.org/sailing/images/2006-11-17__sun__600_800.jpg" alt="Water" /></a>
        </li>
    </ul>
</div>

的Javascript

$('.selected').fadeIn();
$("#gallery ul li").on("click", function () {
    var selector = '#gallery ul li[src="' + $(this).attr('href') + '"]';

    $(".selected").hide();

    $("#gallery ul li").fadeIn();
    return false;
});

$('#gallery ul li img').on('click', function () {
    $(".selected").hide();
    var next = $(this).next();
    if (next.length > 0) {
        next.fadeIn();
    } else {
        $('.selected').fadeIn();
    }
    return false;
});

2 个答案:

答案 0 :(得分:1)

你搞砸了很多东西。首先,你永远不会在框架中显示点击的照片。其次,当您单击锚点内的照片时,默认情况下会将您带到锚点的href(您需要添加e.preventDefault()以防止这种情况,同时确保传递e参数在点击功能 - 功能(e)

HTML

<div id="photo">
        <img src="http://hd.highresolution-wallpapers.net/wallpapers/space_dimesional_sun-600x800.jpg" alt="Space"/>
    </div>
<div id="gallery">
        <ul>
            <li class="selected"><img src="http://hd.highresolution-wallpapers.net/wallpapers/space_dimesional_sun-600x800.jpg" alt="Space" /></li>
            <li><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSh_AgoWSwWBYuvqlbD7kzIrtcPRCV3jGzn5H4fosJRba8JzE1-Ow" alt="Grass" /></li>
            <li><img src="http://sitch.org/sailing/images/2006-11-17__sun__600_800.jpg" alt="Water" /></li>
        </ul>
    </div>

的Javascript

$(document).on('click', '#gallery img', function() {
    $('#photo').attr('src', $(this).attr('src'));
});

答案 1 :(得分:1)

将以下行添加到$('#gallery ul li img').on('click', function (){...}部分:

$('#photo').find('img').prop('src',$(this).prop('src'));

最终结果:

$('#gallery ul li img').on('click', function () {
    $(".selected").hide();
    $('#photo').find('img').prop('src',$(this).prop('src'));

    window.location.href="#photo";
    return false;
});

Live Demo