setting a whole style string to an element from javascript (not individual style parameters)

前端 未结 3 743
抹茶落季
抹茶落季 2020-12-09 08:06

I need to set an arbitrary style to a span via javascript.

I know I can do things like: span.style.height=\"250px\"; But I need to be able to insert a r

3条回答
  •  再見小時候
    2020-12-09 08:54

    If you want it to be lightweight, create a function such as:

    function setStyles(element, styles)
    {
        for(var s in styles) {
            element.style[s] = styles[s];
        }
    }
    

    Then you would pass the styles in as an object literal:

    setStyles(element, {float: "left",
                        textDecoration: "underline",
                        cursor: "pointer",
                        color: "blue"});
    

    Note that the style references passed in have to follow the naming from a JavaScript standpoint, since the function simply changes the styles by accessing the element's style object through JavaScript.

    If you must take your style input from a string then you could quite easily parse it and create the object literal.

提交回复
热议问题