我是 jQuery 的新手,几乎没有编程经验,所以请考虑到这一点。
我创建了一个节省时间的脚本,它将采用以下两个变量:
1) 一个元素(包含单个图像)- imgelement
2) 悬停图像的图像 URL - hoverimageurl
代码:
/* Image Hover Script (Start) */
var imgelement = "#element"; /* Element containing the original image */
var hoverimageurl = "http://www.domain.com/image.png2"; /* Image URL of the hover image */
jQuery(document).ready(function() {
/* Add CSS and a class to the original image to fix positioning and give it an identification */
jQuery(imgelement + " img").addClass("originalimage");
/* Prepend hover image to the element. Set the SRC to the hover image URL */
jQuery(imgelement).prepend('<img class="hoverimage" src="' + hoverimageurl + '">');
/* Fade out original image and fade in hover image on hover */
jQuery(imgelement).hover(function() {
jQuery(imgelement + " .originalimage").stop(true).fadeTo(1000, 0);
jQuery(imgelement + " .hoverimage").stop(true).fadeTo(1000, 1);
}, function() {
jQuery(imgelement + " .hoverimage").stop(true).fadeTo(1000, 0);
jQuery(imgelement + " .originalimage").stop(true).fadeTo(1000, 1);
});
});
/* Image Hover Script (End) */
/* Image Hover CSS (Start) */
#pix-fe .originalimage {
position: relative;
}
#pix-fe .hoverimage {
position: absolute;
width: 100%;
height: 100%;
}
/* Image Hover CSS (End) */
<div class="element">
<a href="http://www.domain.com"><img src="http://www.domain.com/image1.png"></a>
</div>
当元素悬停时,脚本所做的是淡化到 hoverimageurl
变量给出的悬停图像。这非常有效,但我想使用此脚本的多个实例,为此我需要为我需要的每个实例附加一个递增数字的变量名。这是低效的,因为在理想情况下我只想要一个变量列表和一个主脚本实例时,大部分脚本都需要在每个实例中重复。
有什么方法可以实现这段代码的泛化吗?我知道 this
但 imgelement
将始终具体引用 imgelement
变量的值,因此据我所知我看不出这是怎么回事完成。
非常感谢您的宝贵时间。
最佳答案
没有什么是小 css 无法处理的:)
.image-switch {
position: relative;
}
.image-switch img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
opacity: 1;
transition: opacity 1s
}
.image-switch:hover img:last-child{
opacity: 0
}
<span class="image-switch">
<img src="http://placehold.it/200x200/FF0000">
<img src="http://placehold.it/200x200">
</span>
关于javascript - 这个脚本有可能被通用化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975522/