我完全不(完全)熟悉JQuery,只能在藍色的月亮中蘸一下腳趾。然而,我需要我根本無法找到一個快速解決方案 - 儘管我相信這樣一個快速解決方案必須可用:)JQuery - 查找圖像,添加來自attr的標題
我有一個div,其中的圖像可能會在文本之間浮動。我想掃描那個div,選擇其中的所有圖像(如果有的話),給他們一個課,給他們添加一個<p></p>
,並將<img>
和匹配<p>
放在他們自己的包裝div中。在創建的段落塊中,我想要放置所述圖像的標題屬性。
我已經試過谷歌和這裏,但都塗有片段處理插件,而我只是想要一個即插即用片段,我可以放在我包括的js文件中。我試圖從JQuery網站上的東西中拼湊出自己的東西,但這是一團糟。
任何幫助都非常感謝!
編輯:使用由以下@ Xeon06提供了答案,我的完成工作溶液,如下所示:
$(".lorem img").each(function() {
$(this).addClass("inline-img");
$(this).wrap("<div>");
if ($(this).prop("title")!='') {
$("<p>").text($(this).prop("title")).insertAfter($(this));
}
});
$(".lorem div").each(function() {
$(this).addClass("inline-img-wrap");
});
$(".inline-img").each(function() {
var mTop = $(this).css('marginTop');
var mBottom = $(this).css('marginBottom');
var mLeft = $(this).css('marginLeft');
var mRight = $(this).css('marginRight');
var thisfloat = $(this).css('float');
$(this).parent().css('marginTop', mTop);
$(this).css('marginTop', '');
$(this).parent().css('marginBottom', mBottom);
$(this).css('marginBottom', '');
$(this).parent().css('marginLeft', mLeft);
$(this).css('marginLeft', '');
$(this).parent().css('marginRight', mRight);
$(this).css('marginRight', '');
$(this).parent().css('float', thisfloat);
$(this).css('float', '');
});
代碼的最後部分是採取的圖像的主定位屬性(裕度和浮動)並將它們應用於之前創建的包裝div。然後,我從圖像中自己抹去這些值以避免加倍。打擾一下noobish編碼吧!
你實際上不能追加anythi ng''標籤,但您可以在''之後附加它。 – Blazemonger 2012-01-05 20:25:23
如果你的意思是它會在圖片標籤後出現,那就沒問題了。假設兩者都將包裹在他們自己的div中。 – Eamonn 2012-01-05 20:28:35