在<style>中查找并替换url

时间:2018-08-30 18:42:29

标签: javascript jquery replace find

我有这个CSS:

  
 

现在我想查找并替换以下网址: /img/thumbs.jpg http://abc.xyz/img/no-thumb.jpg < / p>

有可能吗?

3 个答案:

答案 0 :(得分:1)

  

尝试:

$(document).ready(function(){
    var background = $('.thumbs').css('background');
    var a = background.split('"');
    var new_image = '';

     $.each(a,function(index, element){
        var str = element.split('/').slice(3,5).join('/');
        if(str == 'img/thumbs.jpg'){
          new_image = 'http://abc.xyz/img/no-thumb.jpg';
        }
    })

    if(new_image !=''){
        $('.thumbs').css('background',"url('"+new_image+"') no-repeat");
    }
})

答案 1 :(得分:0)

 window.onload = function(){
       document.getElementByClassName('thumbs').style.background = "url('http://abc.xyz/img/no-thumb.jpg')";
   }

答案 2 :(得分:0)

您可以使用其他实例覆盖thumbs CSS类:

<script type="text/javascript">
    // once head is loaded add style element with class definition that will override .thumbs
    var head = document.getElementsByTagName('head')[0]; // get head dom element
    head.innerHTML += '<style> .thumbs{background:url("https://www.toptal.com/designers/subtlepatterns/patterns/leaves.png") no-repeat;}</style>'; // put additional style at the end of head (this will overide thumbs), you can put any url background here. 
</script>   

下面的工作示例(https://jsbin.com/mehuhokopi/edit?html,output):

<html>
  <head>
    <style> .thumbs{background:url('/img/thumbs.jpg') no-repeat;}</style>
    <style>
      .test {
        width: 100%;
        height: 100%;
        background-color: red;
      }      
    </style>
    <script type="text/javascript">
        // once head is loaded add style element with class definition that will override .thumbs
        var head = document.getElementsByTagName('head')[0]; // get head dom element
        head.innerHTML += '<style> .thumbs{background:url("https://www.toptal.com/designers/subtlepatterns/patterns/leaves.png") no-repeat;}</style>'; // put additional style at the end of head (this will overide thumbs), you can put any url background here. 
    </script>        
  </head>
  <body>
    <div class="test thumbs">
    </div>
  </body>
</html>
相关问题