简易JS图像转换器 [英] Easy JS image changer
本文介绍了简易JS图像转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的onMouseOver和Out图像转换器。
I have a simple onMouseOver and Out image changer.
<div id="img1" onMouseOver="changeBg('imgs/1col.png', 'img1')" onMouseOut="changeBg('imgs/1.png', 'img1')"></div>
<div id="img2" onMouseOver="changeBg('imgs/2col.png', 'img2')" onMouseOut="changeBg('imgs/2.png', 'img2')"></div>
function changeBg (image, id) {
var div = document.getElementById(id);
div.style.backgroundImage = "url("+image+")";
}
但是我喜欢50想要应用这种效果的图像,是否有更简单的方法来编写它,作为一个JS函数自动计数并让它返回值等?所以喜欢:
imgs /+ i +col.pngimg+ i
However I have like 50 images I would like to apply this effect on, is there an easier way to write this, as a JS function to count automatically and get it to return values etc? so like: "imgs/" + i + "col.png" "img" + i
感谢所有帮助
编辑:任何人都可以帮忙吗?
anyone able to help on thiss?
推荐答案
HTML:
<!-- Easier to add event handlers at once programmatically -->
<div id="img1">a</div>
<div id="img2">b</div>
JavaScript(注意我正在使用 jQuery ):
The JavaScript (note that I'm using jQuery):
// Retrieve URL from ID
function imgUrlFromId(id, toggle) {
var id = id.replace("img", "");
return "url(imgs/" + id + (toggle ? "col" : "") + ".png)";
}
// Create function defining how to build the URL to the replacement images
function changeImage(e) {
$(e.currentTarget).css("backgroundImage",
imgUrlFromId(e.currentTarget.id, (e.type === "mouseover")));
}
// Bind mouseover and mouseout event handlers to each div with an ID
// starting with "img"
$("div#[id^=img]").each(function() {
$(this).mouseover(changeImage).mouseout(changeImage)
.css("backgroundImage", imgUrlFromId(this.id, false));
});
这篇关于简易JS图像转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文