>  기사  >  웹 프론트엔드  >  태그 제한 없이 요소 스타일을 복제하는 방법

태그 제한 없이 요소 스타일을 복제하는 방법

DDD
DDD원래의
2024-10-22 12:40:02845검색

How to Clone Element Styles Without Tag Restrictions

의사 복제를 위한 복제 요소 스타일

문제:

다음을 수행하는 jQuery 플러그인이 필요합니다. 요소 태그를 제한하지 않고 복제 요소 스타일을 에뮬레이트합니다. 예를 들어 기존 범위의 시각적 모양을 복제하는 양식 입력을 생성할 수 있습니다.

해결책:

이 목적에 적합한 플러그인은 getStyleObject입니다. 이 플러그인은 인라인 스타일을 통해 명시적으로 설정되지 않은 스타일을 포함하여 특정 요소에 대해 계산된 모든 CSS 스타일을 검색합니다.

구현:

<code class="javascript">/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 *
 * Copyright: Unknown, see source link
 * Plugin version by Dakota Schneider (http://hackthetruth.org)
 */

(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);</code>

사용:

한 요소에서 다른 요소로 스타일을 적용하려면 다음 구문을 사용하세요.

<code class="javascript">// original element
var original = $("#original");

// cloned element without styling yet
var cloned = original.clone().appendTo(original.parent());

// get styles from original element
var style = original.getStyleObject();

// apply styles to cloned element
cloned.css(style);</code>

위 내용은 태그 제한 없이 요소 스타일을 복제하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.