2013-09-23 13 views
0

我有這個網站得到一個IMG SRC,然後修改的div容器

<div class="mytext"> 
blablabla 
</div> 

<div class="part2" data-type="background" data-speed="10"> 
    <img src="images/bb4.jpg" /> 
</div> 

<div class="mytext"> 
hello hello world 
</div> 

<div class="part2" data-type="background" data-speed="10"> 
    <img src="images/bb5.jpg" /> 
</div> 

現在我想在第2部分容器中的圖像的每一個SRC,然後更改HTML這一結果

<div class="mytext"> 
blablabla 
</div> 

<div class="part2" style="background:url('images/bb4.jpg') fixed;" data-type="background" data-speed="10"> 

</div> 

<div class="mytext"> 
hello hello world 
</div> 

<div class="part2" style="background:url('images/bb5') fixed;" data-type="background" data-speed="10"> 

</div> 

basicly我得src和再編輯的div容器的屬性,並刪除img標籤,我不得不這樣做頁面

我的負荷寫這篇文章的代碼來獲得sr C,但它不工作,並沒有改變DIV

var elems = [].slice.call(document.getElementsByClassName("post2")); 
elems.forEach(function(elem){ 
    elem.onclick = function(){ 
     var arr = [], 
      imgs = [].slice.call(elem.getElementsByTagName("img")); 
     if(imgs.length){ 
      imgs.forEach(function(img){ 
       var attrID = img.id; 
       arr.push(attrID); 
      }); 
      alert(arr); 
     } else { 
      alert("No images found."); 
     } 
    }; 
}); 

有人可以幫助我的一部分?:) 感謝

+0

你想在香草JavaScript或jQuery的解決辦法嗎?因爲這裏沒有使用jQuery,但是你已經標記了它。你的類名也是'part2',但是你在'post2'上調用'getElementsByClassName'而不是 – CodingIntrigue

+0

jsbin或者jsfiddle鏈接會讓我們更多地幫助你.. – thecodejack

+1

你寫了這段「獲得src的代碼片段」。 ..你甚至不會在你的Javascript代碼中的任何地方提及「src」 – devnull69

回答

1
$('.part2').each(function(){ 
    img = $(this).find('img'); 
    $(this).css({'background': 'url(' + img.attr('src') + ') fixed'}); 
    img.remove(); 
}); 
+0

添加「固定」到CSS背景,你完成 – devnull69

+0

@ devnull69謝謝,我錯過了那一點。 – Mina

+0

完美這是我正在尋找:)!非常感謝你! –

0

既然你已經加入jQuery的標籤。 Here是jquery中的答案。

$('#test').click(function(){ 
    $('.part2').each(function(){ 
     $(this).attr('style','background:url(\''+ $(this).find('img').attr('src')+'\') fixed;'); 
     $(this).find('img').remove(); 
    }); 
}); 

$('#test').click(function(){ 
     $('.part2').each(function(){ 
      $(this).css('background','url(\''+ $(this).find('img').attr('src')+'\') fixed'); 
      $(this).find('img').remove(); 
     }); 
    }); 
+0

所有答案都是類似的,但這個例子。所以對此+1。 –

+0

您可以使用'.css()'方法代替設置'Styel'(拼寫?)屬性。 – undefined

+0

雅我們甚至可以很容易。但是我按照要求做了。 –