试图将随机图像与其他随机图像交换

时间:2013-10-04 15:23:15

标签: javascript jquery

我有一些李,每张都有一张图片。前三个是可见的,其余的都是隐藏的。我想要做的是隐藏一个可见的图像(一个随机的图像 - 这个位有效..),用一个隐藏的图像替换图像并再次显示它,但我似乎无法得到它再次可见。这是codepen:http://codepen.io/anon/pen/sBvkC

HTML:

<ul>
  <li class="imageIn"><img src="http://placehold.it/300x200" /></li>
  <li class="imageIn"><img src="http://placehold.it/300x200" /></li>
  <li class="imageIn"><img src="http://placehold.it/300x200" /></li>
  <li class="imageOut"><img src="http://placehold.it/300x200" /></li>
  <li class="imageOut"><img src="http://placehold.it/300x200" /></li>
</ul>

CSS:

* { margin: 0; padding: 0; }    
ul { list-style-type: none; width: 100%; }
li { width: 33%; display: inline-block; }   
img { width: 100%; }    
.imageOut { display: none; }   
.hidden { visibility: hidden; }    
.visible { visibility: visible; }

JS:

window.setInterval(function(){swapImage()},1000);

function swapImage() {

  /* select random image that is currently displayed */
 ins = $('.imageIn > img');
 var imageDisplayed = $(ins[Math.floor(Math.random()*ins.length)]);

  /* select random image that is NOT currently displayed */
  outs = $('.imageOut > img');   
  var imageNotDisplayed = $(outs[Math.floor(Math.random()*outs.length)]);

  /* switch displayed image to visibility:hidden */
  $(imageDisplayed).css("visibility", "hidden");

  /* SWAP src of imageDisplayed with that of imageNotDisplayed */
  var srcDisplayed = $(imageDisplayed).attr("src");
  var srcNotDisplayed = $(imageNotDisplayed).attr("src");
  $(imageDisplayed).attr("src") = srcNotDisplayed;
  $(imageNotDisplayed).attr("src") = srcDisplayed;

  /* switch to visibility:visible */
  $(imageDisplayed).css("visibility", "visible");

}

我做错了什么?

1 个答案:

答案 0 :(得分:4)

您没有正确设置img标记上的src属性。变化:

$(imageDisplayed).attr("src") = srcNotDisplayed;
$(imageNotDisplayed).attr("src") = srcDisplayed;

分为:

$(imageDisplayed).attr("src", srcNotDisplayed);
$(imageNotDisplayed).attr("src", srcDisplayed);