我有一些图像和它们的翻转图像。使用jQuery,我想在onmousemove/onmouseout事件发生时显示/隐藏滚动图像。我所有的图像名称都遵循相同的模式,像这样:
原始图片:Image.gif 翻转图像:Imageover.gif
我想分别在onmouseover和onmouseout事件中插入和删除图像源的“over”部分。
如何使用jQuery来实现它?
我有一些图像和它们的翻转图像。使用jQuery,我想在onmousemove/onmouseout事件发生时显示/隐藏滚动图像。我所有的图像名称都遵循相同的模式,像这样:
原始图片:Image.gif 翻转图像:Imageover.gif
我想分别在onmouseover和onmouseout事件中插入和删除图像源的“over”部分。
如何使用jQuery来实现它?
当前回答
$('img.over').each(function(){
var t=$(this);
var src1= t.attr('src'); // initial src
var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
t.hover(function(){
$(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension
}, function(){
$(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
});
});
您可能希望从第一行更改图像的类。如果您需要更多的图像类(或不同的路径),您可以使用
$('img.over, #container img, img.anotherOver').each(function(){
等等。
它应该工作,我没有测试它:)
其他回答
在寻找解决方案的时候,我发现了一个类似于下面的脚本,经过一些调整后,我得到了为我工作。
它处理两个图像,几乎总是默认为“off”,即鼠标不在图像上(image-example_off.jpg),以及偶尔的“on”,即鼠标悬停时,显示所需的替代图像(image-example_on.jpg)。
<script type="text/javascript">
$(document).ready(function() {
$("img", this).hover(swapImageIn, swapImageOut);
function swapImageIn(e) {
this.src = this.src.replace("_off", "_on");
}
function swapImageOut (e) {
this.src = this.src.replace("_on", "_off");
}
});
</script>
如果您有多个图像,并且需要一些不依赖于命名约定的通用图像。
HTML
<img data-other-src="big-zebra.jpg" src="small-cat.jpg">
<img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
<img data-other-src="friendly-bear.jpg" src="penguin.jpg">
JavaScript
$('img').bind('mouseenter mouseleave', function() {
$(this).attr({
src: $(this).attr('data-other-src')
, 'data-other-src': $(this).attr('src')
})
});
准备就绪:
$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("over.gif", ".gif");
$(this).attr("src", src);
});
});
对于那些使用url图像源的:
$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src");
var regex = /_normal.svg/gi;
src = this.src.replace(regex,'_rollover.svg');
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src");
var regex = /_rollover.svg/gi;
src = this.src.replace(regex,'_normal.svg');
$(this).attr("src", src);
});
});
如果你正在寻找的解决方案是一个动画按钮,那么你能做的最好的提高性能的方法是精灵和CSS的结合。精灵是一个巨大的图像,它包含了站点的所有图像(标题、标志、按钮和所有装饰)。您拥有的每个图像都使用一个HTTP请求,HTTP请求越多,加载所需的时间就越多。
.buttonClass {
width: 25px;
height: 25px;
background: url(Sprite.gif) -40px -500px;
}
.buttonClass:hover {
width: 25px;
height: 25px;
background: url(Sprite.gif) -40px -525px;
}
0px 0px坐标将位于精灵的左上角。
但如果您使用Ajax或类似的技术开发相册,那么JavaScript(或任何框架)是最好的。
玩得开心!
$('img').mouseover(function(){
var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
$(this).attr("src", newSrc);
});
$('img').mouseout(function(){
var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
$(this).attr("src", newSrc);
});