요소의 계산 된 스타일을 반환하여 해당 요소를 의사 복제하는 jQuery CSS 플러그인?
jQuery를 사용하여 첫 번째 일치 요소에 대해 계산 된 스타일의 개체를 반환하는 방법을 찾고 있습니다. 그런 다음이 개체를 jQuery의 CSS 메서드의 다른 호출에 전달할 수 있습니다.
예를 들어 width 를 사용하면 다음을 수행하여 두 div의 너비를 동일하게 만들 수 있습니다.
$('#div2').width($('#div1').width());
텍스트 입력을 기존 스팬처럼 보이게 할 수 있다면 좋을 것입니다 .
$('#input1').css($('#span1').css());
인수가없는 .css ()는 .css (obj)에 전달할 수있는 객체를 반환합니다 .
(이에 대한 jQuery 플러그인을 찾을 수 없지만 존재해야하는 것 같습니다. 존재하지 않는 경우 아래 내 플러그인을 플러그인으로 바꾸고 사용하는 모든 속성과 함께 게시하겠습니다.)
기본적으로 특정 요소를 의사 복제하고 싶지만 다른 태그를 사용합니다 . 예를 들어, 숨기고 싶은 li 요소가 있고 그 위에 똑같이 보이는 입력 요소를 놓습니다. 사용자 가 입력하면 요소를 인라인으로 편집하는 것처럼 보입니다 .
편집을위한이 의사 복제 문제에 대한 다른 접근 방식도 열려 있습니다. 어떤 제안?
여기 내가 현재 가지고있는 것이 있습니다. 유일한 문제는 가능한 모든 스타일을 얻는 것입니다. 이것은 엄청나게 긴 목록 일 수 있습니다.
jQuery.fn.css2 = jQuery.fn.css;
jQuery.fn.css = function() {
if (arguments.length) return jQuery.fn.css2.apply(this, arguments);
var attr = ['font-family','font-size','font-weight','font-style','color',
'text-transform','text-decoration','letter-spacing','word-spacing',
'line-height','text-align','vertical-align','direction','background-color',
'background-image','background-repeat','background-position',
'background-attachment','opacity','width','height','top','right','bottom',
'left','margin-top','margin-right','margin-bottom','margin-left',
'padding-top','padding-right','padding-bottom','padding-left',
'border-top-width','border-right-width','border-bottom-width',
'border-left-width','border-top-color','border-right-color',
'border-bottom-color','border-left-color','border-top-style',
'border-right-style','border-bottom-style','border-left-style','position',
'display','visibility','z-index','overflow-x','overflow-y','white-space',
'clip','float','clear','cursor','list-style-image','list-style-position',
'list-style-type','marker-offset'];
var len = attr.length, obj = {};
for (var i = 0; i < len; i++)
obj[attr[i]] = jQuery.fn.css2.call(this, attr[i]);
return obj;
}
편집 : 나는 지금 한동안 위의 코드를 사용하고 있습니다. 그것은 잘 작동하며, 한 가지 예외를 제외하고는 원래의 css 메소드와 똑같이 동작합니다. 만약 0 개의 인자가 전달되면 계산 된 스타일 객체를 반환합니다.
보시다시피, 해당되는 경우 원래 CSS 메서드를 즉시 호출합니다. 그렇지 않으면 나열된 모든 속성의 계산 된 스타일을 가져옵니다 (Firebug의 계산 된 스타일 목록에서 수집). 긴 값 목록을 얻고 있지만 매우 빠릅니다. 다른 사람들에게 유용하기를 바랍니다.
2 년 늦었지만 당신이 찾고있는 해결책이 있습니다. 여기 내가 작성한 플러그인이 있습니다 (다른 사람의 기능을 플러그인 형식으로 래핑하여). 원하는대로 정확히 수행하지만 모든 브라우저, 심지어 IE에서도 가능한 모든 스타일을 가져 옵니다.
jquery.getStyleObject.js:
/*
* 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);
기본 사용법은 매우 간단합니다.
var style = $("#original").getStyleObject(); // copy all computed CSS properties
$("#original").clone() // clone the object
.parent() // select it's parent
.appendTo() // append the cloned object to the parent, after the original
// (though this could really be anywhere and ought to be somewhere
// else to show that the styles aren't just inherited again
.css(style); // apply cloned styles
도움이되기를 바랍니다.
jQuery는 아니지만 Firefox, Opera 및 Safari window.getComputedStyle(element)에서는 요소에 대한 계산 된 스타일을 가져 오는 데 사용할 수 있으며 IE <= 8에서는 element.currentStyle. 반환 된 객체는 경우마다 다르며 Javascript를 사용하여 만든 요소와 스타일이 얼마나 잘 작동하는지 잘 모르겠지만 유용 할 것입니다.
Safari에서는 다음을 수행 할 수 있습니다.
document.getElementById('b').style.cssText = window.getComputedStyle(document.getElementById('a')).cssText;
지금까지받은 답변에 만족하는지 모르겠지만 저도 그렇지 않았고 저도 당신을 기쁘게하지 않을 수도 있지만 다른 사람에게 도움이 될 수 있습니다.
요소의 스타일을 서로 "복제"하거나 "복사"하는 방법을 숙고 한 후 n을 반복하고 n2에 적용하는 것이 최적의 방법이 아니라는 것을 깨달았습니다. .
이러한 문제에 직면했을 때 한 요소에서 다른 요소로 모든 스타일을 복사 할 필요가 거의 없습니다. 일반적으로 "일부"스타일을 적용하려는 특정 이유가 있습니다.
되 돌린 내용은 다음과 같습니다.
$.fn.copyCSS = function( style, toNode ){
var self = $(this);
if( !$.isArray( style ) ) style=style.split(' ');
$.each( style, function( i, name ){ toNode.css( name, self.css(name) ) } );
return self;
}
다음과 같이 공백으로 구분 된 css 속성 목록을 첫 번째 인수로 전달하고 복제하려는 노드를 두 번째 인수로 전달할 수 있습니다.
$('div#copyFrom').copyCSS('width height color',$('div#copyTo'));
그 이후로 "잘못 정렬"된 것처럼 보이는 것이 무엇이든지간에, 잘못된 아이디어가 너무 많은 Js를 어지럽히 지 않도록 스타일 시트를 수정하려고 노력할 것입니다.
이제 문제를 조사하고 jQuery의 내부 CSS 방법이 어떻게 작동하는지 더 잘 이해할 시간이 있었으므로 내가 게시 한 내용은 내가 언급 한 사용 사례에 충분히 잘 작동하는 것 같습니다.
CSS로이 문제를 해결할 수 있다고 제안되었지만, 이것은 제거 클래스를 추가하거나 CSS를 업데이트하지 않고도 어떤 경우에도 작동하는보다 일반적인 솔루션이라고 생각합니다.
다른 사람들이 유용하다고 생각하기를 바랍니다. 버그를 찾으면 알려주세요.
나는 귀하의 답변 Quickredfox를 좋아합니다. 일부 CSS를 복사해야했지만 즉시는 아니기 때문에 "toNode"를 선택 사항으로 만들도록 수정했습니다.
$.fn.copyCSS = function( style, toNode ){
var self = $(this),
styleObj = {},
has_toNode = typeof toNode != 'undefined' ? true: false;
if( !$.isArray( style ) ) {
style=style.split(' ');
}
$.each( style, function( i, name ){
if(has_toNode) {
toNode.css( name, self.css(name) );
} else {
styleObj[name] = self.css(name);
}
});
return ( has_toNode ? self : styleObj );
}
다음과 같이 부르면 :
$('div#copyFrom').copyCSS('width height color');
그런 다음 나중에 사용할 수 있도록 CSS 선언과 함께 객체를 반환합니다.
{
'width': '140px',
'height': '860px',
'color': 'rgb(238, 238, 238)'
}
시작해 주셔서 감사합니다.
다목적 .css()
용법
$('body').css(); // -> { ... } - returns all styles
$('body').css('*'); // -> { ... } - the same (more verbose)
$('body').css('color width height') // -> { color: .., width: .., height: .. } - returns requested styles
$('div').css('width height', '100%') // set width and color to 100%, returns self
$('body').css('color') // -> '#000' - native behaviour
암호
(function($) {
// Monkey-patching original .css() method
var nativeCss = $.fn.css;
var camelCase = $.camelCase || function(str) {
return str.replace(/\-([a-z])/g, function($0, $1) { return $1.toUpperCase(); });
};
$.fn.css = function(name, value) {
if (name == null || name === '*') {
var elem = this.get(0), css, returns = {};
if (window.getComputedStyle) {
css = window.getComputedStyle(elem, null);
for (var i = 0, l = css.length; i < l; i++) {
returns[camelCase(css[i])] = css.getPropertyValue(css[i]);
}
return returns;
} else if (elem.currentStyle) {
css = elem.currentStyle;
for (var prop in css) {
returns[prop] = css[prop];
}
}
return returns;
} else if (~name.indexOf(' ')) {
var names = name.split(/ +/);
var css = {};
for (var i = 0, l = names.length; i < l; i++) {
css[names[i]] = nativeCss.call(this, names[i], value);
}
return arguments.length > 1 ? this : css;
} else {
return nativeCss.apply(this, arguments);
}
}
})(jQuery);
주요 아이디어는 Dakota의 & HexInteractive의 답변 에서 가져옵니다 .
OP가 제공하는 훌륭한 기능. 반환 할 값을 선택할 수 있도록 약간 수정했습니다.
(function ($) {
var jQuery_css = $.fn.css,
gAttr = ['font-family','font-size','font-weight','font-style','color','text-transform','text-decoration','letter-spacing','word-spacing','line-height','text-align','vertical-align','direction','background-color','background-image','background-repeat','background-position','background-attachment','opacity','width','height','top','right','bottom','left','margin-top','margin-right','margin-bottom','margin-left','padding-top','padding-right','padding-bottom','padding-left','border-top-width','border-right-width','border-bottom-width','border-left-width','border-top-color','border-right-color','border-bottom-color','border-left-color','border-top-style','border-right-style','border-bottom-style','border-left-style','position','display','visibility','z-index','overflow-x','overflow-y','white-space','clip','float','clear','cursor','list-style-image','list-style-position','list-style-type','marker-offset'];
$.fn.css = function() {
if (arguments.length && !$.isArray(arguments[0])) return jQuery_css.apply(this, arguments);
var attr = arguments[0] || gAttr,
len = attr.length,
obj = {};
for (var i = 0; i < len; i++) obj[attr[i]] = jQuery_css.call(this, attr[i]);
return obj;
}
})(jQuery);
고유 한 배열을 지정하여 원하는 값을 선택하십시오. $().css(['width','height']);
I just wanted to add an extension to the code submitted by Dakota.
If you want to clone an element with all of the styles applied to it and all the children elements then you can use the following code:
/*
* 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();
}
$.fn.cloneWithCSS = function() {
styles = {};
$this = $(this);
$clone = $this.clone();
$clone.css( $this.getStyleObject() );
children = $this.children().toArray();
var i = 0;
while( children.length ) {
$child = $( children.pop() );
styles[i++] = $child.getStyleObject();
$child.children().each(function(i, el) {
children.push(el);
})
}
cloneChildren = $clone.children().toArray()
var i = 0;
while( cloneChildren.length ) {
$child = $( cloneChildren.pop() );
$child.css( styles[i++] );
$child.children().each(function(i, el) {
cloneChildren.push(el);
})
}
return $clone
}
})(jQuery);
Then you can just do: $clone = $("#target").cloneWithCSS()
$.fn.cssCopy=function(element,styles){
var self=$(this);
if(element instanceof $){
if(styles instanceof Array){
$.each(styles,function(val){
self.css(val,element.css(val));
});
}else if(typeof styles===”string”){
self.css(styles,element.css(styles));
}
}
return this;
};
Use example
$("#element").cssCopy($("#element2"),['width','height','border'])
'Program Club' 카테고리의 다른 글
| C ++에서 생성자와 소멸자가 인라인 함수가 될 수 있습니까? (0) | 2020.11.11 |
|---|---|
| '더 똑똑한'방식으로 파이썬을 사용하여 파일을 다운로드하는 방법은 무엇입니까? (0) | 2020.11.11 |
| 전화 통화를위한 URL 체계 (0) | 2020.11.11 |
| 포함 파일이 저장된 위치-Ubuntu Linux, GCC (0) | 2020.11.11 |
| 번호로 신용 카드 유형을 결정합니까? (0) | 2020.11.11 |