Jquery 图像切换
我正在为我正在构建的网站使用 Jquery 中的图像切换功能。有大量的项目,所以我对这些图像进行了大量压缩。然而,其中一些 .gif 看起来并不好看,只有制作 .jpg 才有意义。
我的问题是,此代码仅将一个图像交换为另一个名称不同但前缀相似的图像。有没有办法只交换文件名,这样如果我有 .gif 或 .jpg,那没关系,因为它只是将名称从 _static 交换到 _rollover 吗?
这是我正在使用的代码:
//Image Switch
$(document).ready(function(){
$(".projectThumb img").hover(
function(){
var iconName = $(this).attr("src");
var origin = iconName.split("_static.")[0];
$(this).attr({src: "" + origin + "_rollover.gif"});
},
function(){
var iconName = $(this).attr("src");
var origin = iconName.split("_rollover.")[0];
$(this).attr({src: "" + origin + "_static.gif"});
});
});
以及图像切换的 HTML
<div class="projectThumb">
<img src="/img/mr_button_static.gif" class="button" name="mr">
<p class="title">Title – Poster</p>
</div>
要切换的图像名为 /img/mr_button_rollover.jpg
谢谢!
I am using an image switch function in Jquery for a site I am building. There are a ton of projects so I am heavily compressing a lot of these images. Some of them however dont look nice as .gifs and it really only makes sense to make a .jpg.
My problem is that this code only swaps one image, to another image of a different name but similar prefix. Is there a way to swap just the name of the file, so that if I have a .gif, or .jpg, it wouldn't matter as it would just be swapping the name from _static to _rollover?
Here is the code I am using:
//Image Switch
$(document).ready(function(){
$(".projectThumb img").hover(
function(){
var iconName = $(this).attr("src");
var origin = iconName.split("_static.")[0];
$(this).attr({src: "" + origin + "_rollover.gif"});
},
function(){
var iconName = $(this).attr("src");
var origin = iconName.split("_rollover.")[0];
$(this).attr({src: "" + origin + "_static.gif"});
});
});
and the HTML for the image switch
<div class="projectThumb">
<img src="/img/mr_button_static.gif" class="button" name="mr">
<p class="title">Title – Poster</p>
</div>
The image to be switched is named /img/mr_button_rollover.jpg
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用字符串替换即可在图像名称中的静态和翻转之间切换。
如果图像前缀有可能静态/翻转,只需在搜索和替换字符串中包含下划线,并匹配/替换文件扩展名之前的点。
Just use string replacement to switch between static and rollover in the image name.
If there is a possibility that you could static/rollover in the image prefix, simply include the underscore in the search and replace strings and match/replace the dot before the file extension.