简体   繁体   English

带有多个图像和getElementById的JavaScript SwapImage

[英]JavaScript SwapImage with multiple images and getElementById

I wanted to implement a swapImage on my site that would swap one image on mouseover , and another image on mouseout . 我想在我的网站上实现一个swapImage ,它可以在mouseover上交换一个图像,在mouseout上交换另一个图像。 Essentially, with the solution I found I could also probably swap different images for mousedown and mouseup even. 基本上,通过我发现的解决方案,我甚至可以为mousedownmouseup交换不同的图像。

I have this happening in 8 different nested tabs, all of which are on the same page. 我在8个不同的嵌套选项卡中发生了这种情况,所有这些选项卡都位于同一页面上。

The javascript looks like this: javascript看起来像这样:

<script type="text/javascript">
    function swapImageFiat(imgID, imgSrc) {
        var theImage = document.getElementById(imgID)
        theImage.src = imgSrc;
    }

    function swapImageHarley(imgID, imgSrc) {
        var theImage = document.getElementById(imgID)
        theImage.src = imgSrc;
    }

    function swapImageHotWheels(imgID, imgSrc) {
        var theImage = document.getElementById(imgID)
        theImage.src = imgSrc;
    }

    function swapImageVoltron(imgID, imgSrc) {
        var theImage = document.getElementById(imgID)
        theImage.src = imgSrc;
    }

    function swapImageBenchmade(imgID, imgSrc) {
        var theImage = document.getElementById(imgID)
        theImage.src = imgSrc;
    }

    function swapImageCrew(imgID, imgSrc) {
        var theImage = document.getElementById(imgID)
        theImage.src = imgSrc;
    }

    function swapImageReuters(imgID, imgSrc) {
        var theImage = document.getElementById(imgID)
        theImage.src = imgSrc;
    }

    function swapImageMarsVolta(imgID, imgSrc) {
        var theImage = document.getElementById(imgID)
        theImage.src = imgSrc;
    }

    function preLoadImages() {
        for(var i = 0; i < arguments.length; i++) {
            var theImage = new Image();
            theImage.src = arguments[i];
        }
    }
</script>

And the inline code for each image would be essentially this: 每个图像的内联代码基本上都是这样的:

<img class="diagram" src="img/fiat.gif" id="imgToSwapFiat" alt="Diagram" data-title="Fiat Diagram" onClick="swapImageFiat('imgToSwapFiat', 'img/fiat-animated.gif')" onmouseout="swapImageFiat('imgToSwapFiat', 'fiat.gif')" height="189" width="358" />  

I would like to be able to use less IDs , less of the same repetitive script, and shorter inline code. 我希望能够使用更少的ID ,更少的相同重复脚本和更短的内联代码。
But I also want the flexibility of being able to just change the images and their IDs, rather than fussing with JQuery or other script. 但我也希望是能够只是改变图像和它们的ID,而不是使用jQuery或其他脚本大惊小怪的灵活性。 This is why I'm using getElementById . 这就是我使用getElementById

Is there a more efficient way for me to write that JavaScript, and/or Inline code? 我是否有更有效的方式来编写JavaScript和/或内联代码?

Also

Is there a way for the image to swap back to the original after the animation stops playing , rather than on mouse-out? 有没有办法让图像在动画停止播放换回原始图像,而不是鼠标移出?

Use this instead of the element ID since your function eventually need the actual element object. 使用this而不是元素ID,因为您的函数最终需要实际的元素对象。

The script example: 脚本示例:

function swapImageFiat(imgEle, imgSrc) {
    imgEle.src = imgSrc;
}

The image HTML example: 图片HTML示例:

<img src="initial.jpg" onclick="swapImageFiat(this, 'clicked.jpg')" onmouseover="swapImageFiat(this, 'hovered.jpg')" onmouseout="swapImageFiat(this, 'left.jpg')" />

Yeah, sure there is. 是的,确定有。 As Jan mentions - all of your functions are identical. 正如Jan提到的那样 - 你的所有功能都是相同的。 There's no need to duplicate them all. 没有必要全部复制它们。 Also, you can remove the inline event-handler code from your html, simply attaching the mouseover/mouseout or mousedown/mouseup. 此外,您可以从html中删除内联事件处理程序代码,只需附加mouseover / mouseout或mousedown / mouseup。

Simply add a new attribute to each image that you wish to have the effect for, then runs some js on page-load to attach the handler. 只需为您希望产生效果的每个图像添加一个新属性,然后在页面加载上运行一些js以附加处理程序。

Here, I've just used (and checked for the existance of) custom attributes. 在这里,我刚刚使用(并检查了存在)自定义属性。 If the image has them, I attach handlers. 如果图像有它们,我附上处理程序。 If not, it's no different to any other normal image. 如果没有,它与任何其他正常图像没有区别。 This should be nice an re-usable and little effort to use. 这应该是一个很好的可重用和很少使用的努力。

As for resetting the image once the animated gif has played, I'd probably look at Jan's first suggestion. 至于动画gif播放后重置图像,我可能会看看Jan的第一个建议。 A slight modification on the idea would be to make the last frame transparent, then simply position the animated image over (z-index higher) the static one. 对该想法进行略微修改将使最后一帧变得透明,然后简单地将动画图像定位在静态图像上(z-index higher)。 When it's done, you'll see the original image again. 完成后,您将再次看到原始图像。 You'll have to decide on a system for refreshing these images, should they need to be re-played. 如果需要重新播放,您必须决定刷新这些图像的系统。 I'm not sure, perhaps setting their src to '', before setting it back to the animated.gif would cause the animation to play from the start again - you'd have to check if to decided to attempt such an approach. 我不确定,或许将他们的src设置为'',然后再将它设置回animated.gif会导致动画再次从头开始播放 - 你必须检查是否决定尝试这样的方法。

<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}

function mInit()
{
    var imgList = document.getElementsByTagName('img');
    var i, n = imgList.length;
    for (i=0; i<n; i++)
    {
        if (imgList[i].hasAttribute('img2'))
            imgList[i].addEventListener('click', imgClick, false);
        if (imgList[i].hasAttribute('img3'))
            imgList[i].addEventListener('mouseover', imgHover, false);
        if (imgList[i].hasAttribute('img4'))
            imgList[i].addEventListener('mouseout', imgOut, false);
    }
}

// because these function are attached with addEventListener, the 'this'
// keyword refers to the image element itself. No need for IDs..
function imgClick()
{
    this.src = this.getAttribute('img2');
}
function imgHover()
{
    this.src = this.getAttribute('img3');
}
function imgOut()
{
    this.src = this.getAttribute('img4');
}


window.addEventListener('load', mInit, false);

</script>
<style>
</style>
</head>
<body>
    <img src='img/gladiators.png'>  <!-- this image won't be touched, as it doesn't have img1, img2 or img3 attributes -->
    <img src='img/opera.svg' img2='img/chromeEyes.svg' img3='img/rss16.png' img4='img/girl2.png'/>
</body>
</html>

Jay has a good suggestion for your functions, which all do the same thing. Jay对你的功能提出了很好的建议,这些功能都是同样的。 If you remove the names from your functions you'll see they are otherwise identical. 如果从功能中删除名称,您将看到它们在其他方面完全相同。 And the function name makes no difference at all, in this case it's just the arguments you pass to the function that matters. 并且函数名称完全没有区别,在这种情况下,它只是传递给重要函数的参数。

Is there a way for the image to swap back to the original after the animation stops playing, rather than on mouse-out? 有没有办法让图像在动画停止播放后换回原始图像,而不是鼠标移出?

You could make the gifs non-looping and make the last frame of the animation the same as the original image. 您可以使GIF非循环,并使动画的最后一帧与原始图像相同。 AFAIK there's no way to detect which frame an animated gif is on through Javascript. AFAIK无法通过Javascript检测动画gif所在的帧。

If you really want it to return to the original image, you could animate the image completely through Javascript: Write a function that preloads all the images (or a spritemap) and then load them frame by frame. 如果你真的希望它返回到原始图像,你可以通过Javascript完全动画图像:编写一个预加载所有图像(或一个spritemap)的函数,然后逐帧加载它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM