图像替换脚本(jQuery)

时间:2011-08-18 15:20:23

标签: jquery

我正在构建一个员工bios页面,其中客户希望选定的缩略图以完全不透明度显示颜色,而所有其他缩略图显示黑色和白色的不透明度较低。哪个不难 - 麻烦的是,每个缩略图都必须具有颜色状态和黑白状态。所以我的下一个想法是在鼠标悬停时换掉黑白图像(将在div中放置颜色背景图像)。

$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});

我的HTML如下:

<div class = "thumbnail" style = "background-image: url(color.jpg);">
<img src="blackandwhite.jpg" />
</div>

显然,既然我在问这个问题,我的想法就行不通了。 mouseover删除innerHTML,变量成功转换,但不会再次插入到DIV中。我错过了什么?

5 个答案:

答案 0 :(得分:2)

而不是交换HTML使用css。

CSS:

.hidden {
     visibility:hidden
}

JS:

$(".thumbnail").hover(
  function () {
    $(this).find('img').addClass('hidden')
  }, 
  function () {
    $(this).find('img').removeClass('hidden')
  }
);

答案 1 :(得分:0)

尝试使用.show()和hide()分别使blackandwhite.jpg图像可见和隐藏。

$(".thumbnail").hover(
  function () {
    $(this).children("img").hide(); //hide b and w on mouse in
  }, 
  function () {
    $(this).children("img").show();  //showb and w on mouse out
  }
);

答案 2 :(得分:0)

当您清空html时,您的mouseleave事件将无法触发,以便再次设置html

工作demo。在这个演示中,我只是设置一个角色节目,你可以看到事件被触发,删除角色,它将无法工作。

答案 3 :(得分:0)

你不需要任何Javascript来做这件事,只需要一块CSS:

 div.thumbnail {
   background-image: url(blackandwhite.jpg);
   opacity: 0.7;
 }
 div.thumbnail:hover {
   background-image: url(color.jpg);
   opacity: 1;
 }

答案 4 :(得分:0)

为什么不尝试使用show和hide方法?一定要指定包含div的宽度,否则隐藏或显示时整个事物都会消失。我猜测缩略图的大小都是一样的,所以很容易添加CSS,例如:

CSS:

.thumbnail
{
   width: 100px;
   height; 100px;
}

的Javascript

$(document).ready(function()
{
   $('img', '.thumbnail').hide();//Start off hidden
   $('.thumbnail').mouseenter(function()
   {
      $('img', this).show();
   });
   $('.thumbnail').mouseleave(function()
   {
      $('img', this).hide();
   });
});