【发布时间】:2010-09-27 11:34:46
【问题描述】:
我正在建立一个照片库,我想做的是让用户滚动图像(假设出于这个问题的目的,它是一张苹果的照片),所有其他图像页面上的苹果也显示其“结束”状态。
我们将不胜感激任何和所有帮助,并提前感谢您的时间!
【问题讨论】:
标签: javascript jquery plugins rollovers
我正在建立一个照片库,我想做的是让用户滚动图像(假设出于这个问题的目的,它是一张苹果的照片),所有其他图像页面上的苹果也显示其“结束”状态。
我们将不胜感激任何和所有帮助,并提前感谢您的时间!
【问题讨论】:
标签: javascript jquery plugins rollovers
您可以将图像的“类型”添加为类。例如一个苹果是:
<img src='' class='apple fruit red' />
您可以拥有任意数量的空格分隔类。
然后添加以下处理程序:
$(".apple").mouseover(function() {
$(".apple").addClass("overState");
});
您需要在 CSS 中定义 overState。在 mouseout 时,您必须删除该类。
【讨论】:
所以每个图像都有许多标签(例如:“apple”、“red”、“big”),当你将鼠标悬停在大红苹果上时,你希望所有其他的苹果、大的东西和红色的东西都亮起来起来了吗?
正如 kgiannakakis 建议的那样,我会将这些数据放入图像的类属性中 - 唯一的区别是我会为每个类添加一些前缀,这样您就不会与页面上的其他类发生冲突。
<img src="the-big-red-apple.jpg" class="tagged tag-big tag-red tag-apple" />
我还在那里添加了一个名为“tagged”的额外类,以便您可以从导航图像或其他任何内容中区分您的标记照片。
$('img.tagged')
.each(function() {
var thisClasses = this.className.split(/s+/); // array of classes.
var search = [];
for (var i = 0; i < thisClasses.length; ++i) {
if (thisClasses[i].substr(0, 4) == "tag-") {
search.push("." + thisClasses[i]);
}
}
$(this).data("tags", search.join(",")); // ".tag-big,.tag-red,.tag-apple"
})
.hover(function() {
$('img.tagged')
.filter(this.data('tags'))
.addClass("highlight")
;
}, function() {
$('img.tagged')
.filter(this.data('tags'))
.removeClass("highlight")
;
})
;
它的作用最初是遍历所有标记的图像,并计算出每个标记上的标记,并将其存储到该元素的 data() 中。这意味着我们只需要这样做一次,而不是每次。
然后它为每个标记的图像添加一个hover 事件以查找与该图像的任何标记匹配的任何内容并添加“highlight”类。同样,当您鼠标移出时,它会删除该类。
【讨论】:
如果这些是链接(锚标记),则不需要 jQuery 来执行此操作。您可以在 CSS 中使用 :hover。
a.apple:hover img {
/* whatever you want to change here */
}
编辑:忽略我。这不会同时更改页面上的所有苹果元素。这就是我在深夜困倦时阅读 SO 得到的结果。
【讨论】:
这种方法实际上会以统一的方式改变图像源,而不是仅仅对它们应用一个类。
function swapImageGroup(imgSelector,suffix){
if (suffix == null) {suffix = "-hover";}
//imgSelector is the jQuery selector to use
//both imgSelector and suffix must be strings
$(selector).hover(
function() {
$(selector).each(function(){
//store ".jpg" or ".png" or whatever as fileExtension
var fileExtension = $(this).attr("src").substr($(this).attr("src").lastIndexOf("."));
//replace something like ".jpg" with something like "-hover.jpg",
//assuming suffix == "-hover"
$(this).attr("src", $(this).attr("src").replace(fileExtension, suffix + fileExtension));
});
},
function() {
$(selector).each(function(){
//chop off the end of the filename, starting at "-hover" (or whatever)
//and put the original extension back on
$(this).attr("src", $(this).attr("src").split(suffix + ".").join("."));
});
}
);
}
所以你会像这样使用函数:
swapImageGroup("img.apple");
或
swapImageGroup("img.foo","-active");
【讨论】: