简体   繁体   English

更改链接悬停上的另一个图像

[英]Change Another Image On Link Hover

The output in HTML is something like this: HTML的输出如下所示:

ProductImage1             ProductImage2       ProductImage3         ProductImage4
Color1 Color2 Color3                          Color2 Color4         Color5 Color6  

What I want to do is when I hover my mouse over any color above, an original (current) image of ProductImage will change to another one (to match the hovered color). 我想做的是,当我将鼠标悬停在以上任何颜色上时,ProductImage的原始(当前)图像将更改为另一图像(以匹配所悬停的颜色)。 And that original image will be back when mouse leaves. 当鼠标离开时,原始图像将返回。

Here is the javascript I've done for hovering over each ProductImage. 这是我为悬停在每个ProductImage上所做的javascript。

var sourceSwap = function () {
    var $this = $(this);
    var newSource = $this.data('alt-src');
    $this.data('alt-src', $this.attr('src'));
    $this.attr('src', newSource);
}
$(function () {
    $('img.main').hover(sourceSwap, sourceSwap);
});

UPDATE UPDATE

I excluded unnecessary parts from my question. 我从问题中排除了不必要的部分。 The answer from @hunter worked very well when I tested it here jsfiddle.net/4dK2x/27. 当我在jsfiddle.net/4dK2x/27对其进行测试时,@ hunter的回答非常有效。 However it didn't work when I combined it with my php parts to create dynamic lists. 但是,当我将其与php部件组合以创建动态列表时,它不起作用。 I'm still looking around and trying to find out the problems. 我仍在四处寻找问题。 I will come back and update my answer if I find a solution for it. 如果找到解决方案,我将回来更新我的答案。

You could do this two ways, you can try it by using CSS: 您可以通过两种方式执行此操作,也可以使用CSS进行尝试:

#tagName{
background: url("yourImage.jpg");
} 
#tagName:hover{
background: url("anotherImage.jpg");
}

this assumes you have a div tag around the image, you can also reference class id's etc. (read into CSS for more details). 假设您在图片周围有一个div标签,还可以引用类ID等等。(更多信息请阅读CSS)。

or you could do it through JavaScript lets say you are not using JQuery (i need to familiarize myself more with JQuery) 或者您可以通过JavaScript做到这一点,比如说您没有使用JQuery(我需要对JQuery更加熟悉)

var image1 = document.getElementById("nameofDivTag");

//on hovering kinda forgotten the JS version of hovering, JQuery has probably easier way

image1.style.background("url:("aDifferentImage.jpg"));

if i am wrong yay! 如果我错了耶! if not yay! 如果不是的话! hope it helps 希望能帮助到你

Here's updated code which should work with as many sets of products as you need if you mimic a similar html structure 如果模拟相似的html结构,则此更新的代码应可与所需的多套产品一起使用

$('.image .toggles img').hover(function () {        
    var src = $(this).attr("src");
    var $main = $(this).closest(".image").find(".main");
    $main.attr("toggle", $main.attr("src")).attr("src", src);
},
function () {        
    var $main = $(this).closest(".image").find(".main");
    $main.attr("src", $main.attr("toggle"));
});

Example: http://jsfiddle.net/4dK2x/1/ 示例: http//jsfiddle.net/4dK2x/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM