S
S
S Pankov2012-04-21 19:30:37
css
S Pankov, 2012-04-21 19:30:37

css to jquery .css()?

How can I automate the copying of the css properties of an element from firebug or the chrome debugger, immediately in the css wrapper from jquery?

There are several dozen elements, you need to create it on the fly.
That is, with this code:

#simple {<br/>
 background-color: red;<br/>
 left:25%;<br/>
 width: 50%;<br/>
 height: 30px;<br/>
 bottom: 0px;<br/>
}<br/>

into something like this
.css({<br/>
 backgroundColor: 'red',<br/>
 left:'25%',<br/>
 width:'50%',<br/>
 height:'30px',<br/>
 bottom:'0px',<br/>
 })<br/>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
laticq, 2012-06-15
@seocoder

I found only a plugin that copies the ALL style of an object

/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 */

(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, l = style.length; i < l; i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            };
            return returns;
        };
        if(style = dom.currentStyle){
            for(var prop in style){
                returns[prop] = style[prop];
            };
            return returns;
        };
        return this.css();
    }
})(jQuery);

// Использовать так
        var style = $("#simple").getStyleObject();
       alert(JSON.stringify(style));
        $('#simple-clone').css(style);

V
Vitaliy Petrychuk, 2012-04-21
@vermilion1

Did not meet, alas.
You can make yourself a page with an input field and listen to the change event of this field. And then execute:

function fix(css) {
  if (!css) return false;
  var obj = {};
  css = css.split('\n').join('').split(' ').join('');
  css = css.slice(css.indexOf('{') + 1, css.indexOf('}') - 1).split(';');
  $.each(css, function(k, prop) {
    prop = prop.split(' ').join('').split(':');
    obj[prop[0]] = prop[1];
  })
  alert('.css(' + JSON.stringify(obj) + '})');
}

fix(_значение_из_поля_ввода_);

Or write a plugin - select the text, press the magic button and the result falls into the clipboard. Which would be really "on the fly" :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question