【问题标题】:Add or remove suffix to image URLS in div为 div 中的图像 URL 添加或删除后缀
【发布时间】:2016-10-09 03:40:18
【问题描述】:

我正在寻找在 .click 函数上使用所需的代码。我有一个深色、浅色的主题切换器,我想在单击深色时将 _dark 添加到某个 div (.the-images) 内的所有图像 url,并在单击浅色时从图像 URL 中删除 _dark。

所以url默认是lalalalala.jpg或者是浅色的,但是点击深色的时候是lalalalala_dark.jpg。

澄清一下 .the-images div 中有大约 20 张图片。它们都有不同的网址,但我想添加到点击功能,以便在点击黑暗时将 _dark 添加到 .jpg 之前的网址中。

更新

因此,有人建议我将深色图像放在 /dark 目录中,这样我只需要更改部分 URL。在网站上使用这些图像的例子有很多,但总是在一个名为“the-images”的 div 中。

所以代码需要是

$(".light").click(function() {
 ### needs /images/name.png for all images in "the-images" div ###
}

$(".dark").click(function() {
 ### needs /images/dark/name.png for all images in "the-images" div ###
}

这将是我现在在我的代码中需要的。感谢大家的帮助

这被其他一些人标记为重复,但我没有看到任何关于如何更改指定 div 内的多个图像 url 的一部分的问题。谢谢你。为了澄清,我已经有了样式切换器(body 类根据用户点击切换暗和亮)。如果打开了深色主题,我现在需要为“the-images”(其中有 20 多个)中的所有图像找到一种方法,使其位于 /dark 目录中。谢谢。

【问题讨论】:

  • 你能发布你已经尝试过的东西吗?

标签: javascript jquery string url append


【解决方案1】:

仅 JavaScript 解决方案

如果所有图像都在img 中,例如将所有dark 图像都在img/dark 中,只需更改相对路径而不是文件名。

var normal = "img/icon-1.png"
console.log(normal)
var dark = normal.replace('img/','img/dark/')
console.log(dark)

这是一种单纯的主题化 可以仅通过 JavaScript 完成的方式。

JavaScript 和 CSS 解决方案

<img class="normal" src="img/icon-1.jpg" />
.normal {
  content: url(img/icon-1.jpg);
}

.dark{
  content: url(img/dark/icon-1.jpg);
}

然后你只需用 JavaScript 更改类。

在特定的&lt;div&gt;做所有图片

使用适当的选择器,选择您想要的&lt;div&gt;,然后循环遍历生成的&lt;img&gt; 标记,并将normal 类替换为dark

类似这样的:

function theme(fromTheme,toTheme) {
    $('.target-div').children('img').map(function(){
        $(this).addClass(fromTheme);
        $(this).removeClass(toTheme);
    });
}

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多