我有一些图像和它们的翻转图像。使用jQuery,我想在onmousemove/onmouseout事件发生时显示/隐藏滚动图像。我所有的图像名称都遵循相同的模式,像这样:
原始图片:Image.gif 翻转图像:Imageover.gif
我想分别在onmouseover和onmouseout事件中插入和删除图像源的“over”部分。
如何使用jQuery来实现它?
我有一些图像和它们的翻转图像。使用jQuery,我想在onmousemove/onmouseout事件发生时显示/隐藏滚动图像。我所有的图像名称都遵循相同的模式,像这样:
原始图片:Image.gif 翻转图像:Imageover.gif
我想分别在onmouseover和onmouseout事件中插入和删除图像源的“over”部分。
如何使用jQuery来实现它?
当前回答
我做了如下代码:)
只有当你有一个名为_hover的第二个文件时,它才有效,例如,facebook.png和facebook_hover.png
$('#social').find('a').hover(function() {
var target = $(this).find('img').attr('src');
//console.log(target);
var newTarg = target.replace('.png', '_hover.png');
$(this).find('img').attr("src", newTarg);
}, function() {
var target = $(this).find('img').attr('src');
var newTarg = target.replace('_hover.png', '.png');
$(this).find('img').attr("src", newTarg);
});
其他回答
我做了如下代码:)
只有当你有一个名为_hover的第二个文件时,它才有效,例如,facebook.png和facebook_hover.png
$('#social').find('a').hover(function() {
var target = $(this).find('img').attr('src');
//console.log(target);
var newTarg = target.replace('.png', '_hover.png');
$(this).find('img').attr("src", newTarg);
}, function() {
var target = $(this).find('img').attr('src');
var newTarg = target.replace('_hover.png', '.png');
$(this).find('img').attr("src", newTarg);
});
$('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(){
等等。
它应该工作,我没有测试它:)
如果你正在寻找的解决方案是一个动画按钮,那么你能做的最好的提高性能的方法是精灵和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(或任何框架)是最好的。
玩得开心!
在寻找解决方案的时候,我发现了一个类似于下面的脚本,经过一些调整后,我得到了为我工作。
它处理两个图像,几乎总是默认为“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>
我知道你在问使用jQuery,但是你可以在浏览器中使用CSS关闭JavaScript来达到同样的效果:
#element {
width: 100px; /* width of image */
height: 200px; /* height of image */
background-image: url(/path/to/image.jpg);
}
#element:hover {
background-image: url(/path/to/other_image.jpg);
}
这里有更长的描述
然而,更好的方法是使用精灵:simple-css-image-rollover