【问题标题】:jQuery: How to add a string to a css propertyjQuery:如何将字符串添加到 CSS 属性
【发布时间】:2016-12-08 22:46:14
【问题描述】:

这就是我想要做的。我有一些背景图像名称为 Look-1.jpg - Look-6.jpg 的 div。我需要做的是一次将 -cut 添加到所有这些,所以基本上将它们更改为 Look-6-cut.jpg。

我尝试这样做的原因是因为我有 2 个背景图像集合,并且我试图在不同的屏幕尺寸上切换它们。

当然可以用 css 做到这一点,但我必须一个一个地做。

我想知道是否有办法使用 jQuery 来实现这一点。

谢谢

<div class="item active" style="background: url('/assets/img/collection/Look-1.jpg') center center no-repeat;">
    <div class="carousel-caption item-caption">
        <h5 class="text-black">200 TC Cotton Percale Duvet Cover</h5>
        <a href="#" class="link-inline">View Product<i class="fa fa-angle-right"></i></a>
    </div>
</div>

【问题讨论】:

  • 嗨 eimansepanta - SO上有很多关于通过 jquery 处理背景图像的问题。做一些研究并尝试一些事情,那么您的查询会得到更好的接收。例如看stackoverflow.com/questions/253689/…

标签: jquery html css background


【解决方案1】:

$("div").css('background-image',(i,cur)=>cur.replace('.jpg','-cut.jpg'));
$("div").each(function(){
  console.log($(this).css('background-image'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item active" style="background: url('/assets/img/collection/Look-1.jpg') center center no-repeat;"></div>
<div class="item active" style="background: url('/assets/img/collection/Look-2.jpg') center center no-repeat;"></div>
<div class="item active" style="background: url('/assets/img/collection/Look-3.jpg') center center no-repeat;"></div>

这对你有用吗?第一行将所有出现的.jpg 替换为-cut.jpg,第二行简单地打印新值来证明这一点。

【讨论】:

    【解决方案2】:
    var backgroundStyle = $(".item").css("background");
    var imageFileName = "someFile.jpg";
    var modifiedImageFileName = "modifiedFileName.jpg";
    backgroundStyle.replace(imageFileName, modifiedImageFileName);
    
    $(".item").css("background", backgroundStyle);
    

    我希望这会有所帮助:)

    【讨论】:

    • 嗨 Gedion D。OP 是否不需要将额外的字符串连接到初始背景图像 url 的末尾,并可能再次将其删除?他提到响应能力是一种雄心壮志,而纵向-横向-纵向似乎需要一个更大的解决方案。只是大声思考。
    • 我只是在这里替换文件名。 Look-1.jpg 到 Look-1-cut.jpg。无需串联。
    【解决方案3】:

    我稍微摆弄了一些虚拟图像,但这也适用于您的 -cut 示例。

    https://jsfiddle.net/5swgrfu6/6/

    $(window).resize(function() {
    var width = $(window).width();
    if (width < 800) {
    $(".item").css({"background": "url('https://dummyimage.com/200x200/ff0000/000') center center no-repeat"});
    } 
    else {
    $(".item").css({"background": "url('https://dummyimage.com/200x200/000000/fff') center center no-repeat"});
     }
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      • 2014-10-24
      相关资源
      最近更新 更多