使用jquery点击其他图像时如何隐藏第一张图像?

时间:2015-10-30 10:28:33

标签: jquery html css image show-hide

jQuery代码 - 我在点击图片时使用图片作为标签,它会在该图像上为我们提供显示内容的其他图像,但是当点击其他图像时,第一张图像不会隐藏。

Fiddle

$(document).ready(function(){

    $('ul.tabs li').click(function(){

        var tab_id = $(this).attr('data-tab');

        $('ul.tabs li').removeClass('current');
        $('.tab-content').removeClass('current');

        $(this).addClass('current');
        $("#"+tab_id).addClass('current');
    });
});

$(function() {

    $("#images").find('img').bind("click", function() {
        var src = $(this).attr("src");

        // Check the beginning of the src attribute  
        var state = (src.indexOf("mainslice") === 0) ? 'mainslice' : 'clr';

        // Modify the src attribute based upon the state var we just set
        (state === 'mainslice') ? src = src.replace('mainslice', 'slice') : src = src.replace('slice', 'mainslice');
        // Apply the new src attribute value  
        $(this).attr("src", src);

        $("#images").hide();
        $("#images").show();

        // This is just for demo visibility
        // $('body').append('<p>' + $(this).attr('src') + '</p>');
    });
});

这是CSS代码:

home {
  background: url(mainslice1.png);
  width: 98px;
  height: 45px;
  line-height: 30px;
  text-align: center;
}

body {
  font-family: Arial, Helvetica, sans-serif;
  line-height: 1.3;
  background: #bdc3c7;
}

h1 {
  font-size: 50px;
  text-align: center;
}

.container {
  width: 700px;
  margin: 0 auto;
}

.tabs {
  background: url(slice3.png);
  margin: 0px;
  padding: 0px;
  list-style: none;
  background: #2c3e50;
  border-bottom: 5px #e67e22 solid;
}

.tabs li {
  display: inline-block;
  margin: 0;
  /*padding: 10px 20px 5px 20px;
    cursor: pointer;

    font-size:1.2em;
    line-height:2em;*/

  color: #FFF;
}

.tabs li:hover {
  background: #d35400;
}

.tabs li.current {
  background: #e67e22;
  color: #FFF;
}

.tab-content {
  background: url(mainslice1.png);
  display: none;
  /*background: #ededed;*/

  padding: 15px;
  line-height: 1.4;
}

.tab-content.current {
  background: url(mainslice1.png);
  display: inherit;
}

2 个答案:

答案 0 :(得分:1)

您需要先隐藏“#images”中的所有图像,然后显示当前点击的图像。

$("img").hide();     //to hide all images
$(this).show();      // to show currently clicked image

答案 1 :(得分:0)

$('img').click(function() {
    $(this).addClass('preserved'); // Add class to mark our image.
    $('img').hide(); // Hide all images.
    $('.preserved').show(); // Show the marked image.
});

您可能希望缩小img选择器范围,使其仅包含所需容器中的图像。