0

我正在编写一个脚本,该脚本在页面上查找特定大小的元素并将它们替换为相同大小的图像。我使用 filter 和 replaceWith 使替换功能正常工作,但是我注意到在测试脚本时我需要复制原始元素的样式以确保它不会与页面的格式发生冲突。

这是我当前可以正常工作的替换脚本:

function findElements(Width,Height) { 
    $("*").filter(function () {
        return $(this).width() == Width && $(this).height() == Height;
    }).replaceWith("<img src='http://mydomain.com/image.jpg'  />");
}

我在 jQuery CSS 插件中找到了一个脚本,它返回元素的计算样式以伪克隆该元素?复制样式。我尝试声明样式变量,但未定义。不知道该怎么办:

(function($){
    $.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            }
            style = window.getComputedStyle(dom, null);
            for(var i=0;i<style.length;i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            }
            return returns;
        }
        if(dom.currentStyle){
            style = dom.currentStyle;
            for(var prop in style){
                returns[prop] = style[prop];
            }
            return returns;
        }
        return this.css();
    }
})(jQuery);    

function findElements(Width,Height) { 
            $("*").filter(function () {
                return $(this).width() == Width && $(this).height() == Height;
                    var style = $(this).getStyleObject();
            }).replaceWith("<img src='http://mydomain.com/image.jpg' style=style='"+ style +"'  />");
        }
4

0 回答 0