1

我想要做的是找到所有具有特定类名的图像,并在它们上面放置一个覆盖图像。到目前为止,我在 jQuery 1.2.6 中的脚本:

jQuery.noConflict();
jQuery(document).ready( function($) {
  var module = $(".module-contactus div div div");
  module.find("img.let").each( function() {
    var iWidth = $(this).width();
    var iHeight = $(this).height();
    var letimg = $('<img src="/LET.png" style="position: absolute; top: 50%; left: 50%; margin-top: -' + Math.ceil(iHeight/2) + 'px; margin-left: -' + Math.ceil(iWidth/2) + 'px;" />');
    var wrapper = $( '<span style="position: relative; display: inline-block;"></span>' );
    $(this).wrap( wrapper );
    letimg.appendTo( wrapper );
  });
});

letimg添加到文档中(根据 Firebug)。该span元素成功地包装了原始图像。此外,如果我传入$(this)appendTo函数,它确实会起作用,但是它会被添加到原始图像中!

编辑:标记如下。(额外的 div 是 Joomla 的结果。)

<div class="module-contactus">
<div><div><div>

<img src="/contact1.jpg" />
<img class="let" src="/contact2.jpg" />

</div></div></div>
</div>

脚本运行后,第二个图像被替换为:

<span style="position: relative; display: inline-block;">
<img class="let" src="/contact2.jpg" />
</span>

但是,它最终应该是这样的:

<span style="position: relative; display: inline-block;">
<img class="let" src="/contact2.jpg" />
<img src="/LET.png" style="..." />
</span>
4

2 回答 2

6

这对我有用:

jQuery.noConflict();
jQuery(function($) {
    $("img.let", $(".module-contactus div div div")).each(function() {
        var iWidth = $(this).width();
        var iHeight = $(this).height();
        var letimg = '<img src="http://www.roomsinworcester.co.uk/images/stories/LET.png" style="position: absolute; top: 50%; left: 50%; margin-top: -' + Math.ceil(iHeight/2) + 'px; margin-left: -' + Math.ceil(iWidth/2) + 'px;" />';
        var wrapper = $('<span style="position: relative; display: inline-block;"></span>');
        $(this).wrap(wrapper).after(letimg);
    });
});

作为旁注。我取出了您的几个变量,并会说您可能可以继续删除其他变量(将 img 标签直接放入 after,将包装器直接放入 wrap 函数等)。不过,这两种方式都不是什么大不了的事。

于 2009-05-05T15:35:09.910 回答
0

我不确定你是否需要包装器。

尝试这样的事情。

jQuery(document).ready( function($) {
    var module = $(".module-contactus div div div");
    module.find("img.let").each( function() {                
        var iWidth = $(this).width();                
        var iHeight = $(this).height();                
        var letimg = $('<img src="http://www.roomsinworcester.co.uk/images/stories/LET.png" style="position: absolute; top: 50%; left: 50%; margin-top: -' + Math.ceil(iHeight/2) + 'px; margin-left: -' + Math.ceil(iWidth/2) + 'px;" />');                
        $(this).before(letimg);         
        alert(module.html());
    });
  });
于 2009-05-05T15:45:08.527 回答