【问题标题】:Switching image source with class not working,切换图像源与类不起作用,
【发布时间】:2020-04-25 09:19:38
【问题描述】:

我正在尝试通过更改图像的源路径来将图像切换到另一个图像,同时在每次切换时添加一个 css 类。但是我现在几个小时都想不出正确的方法。我只是 javascript 的新手。

这是我迄今为止尝试过的:

HTML:

<div class="content">
                <div class="animBox">
                    <img src="images/astroboy2.png" class="astroboy2">
                    <img id="iconsID" src="images/Pencil.png" class="icons"> // this is the image I'm working on.
                </div>
</div>

CSS:

 .icons {
    position: relative;
    top: 30%;
    right: 23%;
    height: 50%;
}

JS:(我已经为图片的路径参考做了一个数组)

let IMG = {
    imageToswitch: document.getElementById("iconsID");
    imagePath: ["images/Ps_Logo.png", "images/Pencil.png", "images/joystick.png"],
    indexPos: 0,

    switching: () => {
    setInterval(() => {
        if (IMGS.indexPos == 2) {
            IMGS.indexPos = 0;
        }
        IMGS.icons.classList.add("icons");
        IMGS.icons.src = IMGS.imagePath[IMGS.indexPos];
        IMGS.indexPos++;
        IMGS.icons.classList.remove("icons");
    }, 900);
}
}

这里唯一起作用的是图像源的切换,但 css 类不起作用,这使得图像的位置和大小不正确。

【问题讨论】:

  • 你正在添加类然后删除它
  • 我知道先生,我的目标是如何正确地切换图像及其 css 类
  • 你为什么添加icons类,然后删除它?

标签: javascript css web


【解决方案1】:

你不能只制作 3 个单独的类来匹配每个来源,然后这样处理吗?

sources = ["src1","src2","src3"];
classes = ["class1","class2","class3"]
x = document.getElementById("eleID");
count = 0;
setInterval(function() {
x.src = sources[count];
x.className = classes[count];
if(count++==2){count=0}
},900)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多