简易JS图像转换器

时间:2011-06-05 17:31:15

标签: javascript image loops

我有一个简单的onMouseOver和Out图像转换器。

<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.png”“img”+ i

感谢您的帮助

编辑:任何人都可以帮忙解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

HTML:

<!-- Easier to add event handlers at once programmatically -->
<div id="img1">a</div>
<div id="img2">b</div>

JavaScript(请注意我正在使用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));
});

答案 1 :(得分:0)

TADA

<强> JavaScript的:

window.onload = function() {
    div = document.getElementById('images').getElementsByTagName('div');
    j = 1;
    for (i = 0; i < div.length; i++) {
        if (div[i].className == 'img') {
            div[i].setAttribute('id', j);
            div[i].style.backgroundImage = 'url(' + j + '.png)';
            div[i].onmouseover = function() {
                this.style.backgroundImage = 'url(' + this.getAttribute('id') + 'col.png)';
            }
            div[i].onmouseout = function() {
                this.style.backgroundImage = 'url(' + this.getAttribute('id') + '.png)';
            }
            j++;
        }
    }
}

<强> HTML:

<div id="images">
    <div class="img"></div>
    <div class="img"></div>
    <div class="img"></div>
    <div class="img"></div>
    <div class="img"></div>
    <div class="img"></div>
    <div class="img"></div>
    <div class="img"></div>
    <div class="img"></div>
    <div class="img"></div>
    ... for as many images you want
</div>