2010-04-08 2 views
1

그것이 VisibleVisible 설정해야하고 다른 모든 Controls (Controls[i]) 아니다 Control (Toggle 최초 OL가 trigers 소자)가 그렇게 될 경우 Hidden.else 절이없는 if 문보다 더 훌륭한 해결책이 있습니까? 다음 코드

의 .js
function Toggle(Control){ 
    var Controls=document.getElementsByTagName("ol",document.getElementById("Quote_App")); 
    var Control=Control.getElementsByTagName("ol")[0]; 
    if(Control.style.visibility!="visible"){ 
     for(var i=0;i<Controls.length;i++){ 
      if(Controls[i]!=Control){ 

       Reveal("hide",20,0.3,Controls[i]); 

      }else{ 

       Reveal("show",20,0.3,Control); 

      }; 
     }; 
    }else{ 

     Reveal("hide",20,0.3,Control); 

    }; 
}; 

함수 [Toggle] 잘 작동하지만

, 실제로 이미하더라도 Hidden Controls[i]에 설정된다.

이 코드는 아래 코드와 같이 If 문을 쉽게 추가 할 수 있습니다. 더 좋은 해결책이 있습니까? 아마도 If이라는 복잡한 조건일까요?

의 .js
function Toggle(Control){ 
    var Controls=document.getElementsByTagName("ol",document.getElementById("Quote_App")); 
    var Control=Control.getElementsByTagName("ol")[0]; 
    if(Control.style.visibility!="visible"){ 
     for(var i=0;i<Controls.length;i++){ 
      if(Controls[i]!=Control){ 

if(Controls[i].style.visibility=="visible"){ 

       Reveal("hide",20,0.3,Controls[i]); 

}; 

      }else{ 

       Reveal("show",20,0.3,Control); 

      }; 
     }; 
    }else{ 

     Reveal("hide",20,0.3,Control); 

    }; 
}; 

당신의 도움이

항상 감사합니다.

+0

버그 :

​NodeList.prototype.forEach = function(f) { for(var i = 0; i <​ this.length; i++) { f.apply(null, [this[i]]); } }; Array.prototype.forEach = NodeList.prototype.forEach; NodeList.prototype.filter = function(f) { var results = []; for(var i = 0; i < this.length; i++) { if(f.apply(null, [this[i]])) { results.push(this[i]); } } return results; }; Array.prototype.filter = NodeList.prototype.filter; NodeList.prototype.hide = function() { this.forEach(function(e) { e.hide(); }); }; Array.prototype.hide = NodeList.prototype.hide; NodeList.prototype.show = function() { this.forEach(function(e) { e.show(); }); }; Array.prototype.show = NodeList.prototype.show; 

이러한 방법은 개별적인 요소에 속성을 적용 요소 목록에 속성을 적용하고있는 NodeList 배열? Control.getElementsByTagName ("ol") [0]; Controls.getElementsByTagName ("ol") [0]이어야합니다. ? – gregmac

+0

버그가 없습니다. Toggle의 인수 Control은 Toggle을 트리거 한 요소입니다. Control 변수는 Control의 첫 번째 자식 OL (Control 인수의 옵션)입니다. –

답변

1
if(Controls[i]!=Control && Controls[i].style.visibility=="visible") { 
    Reveal("hide",20,0.3,Controls[i]); 
} 
+0

명성, 코드가 매우 깨끗합니다. 유감스럽게도 스타일을 특별히 설정하지 않는 한 여기에서 보이는 모든 솔루션은 요소의 스타일을 인라인 또는 자바에서 설정해야합니다. 스타일이 구체적으로 설정되지 않으면 스타일이 표시되지 않습니다. getComputedStyle을 보거나 구체적으로 요소의 가시성을 설정해야합니다. –

+0

@Jay는 Chrome, Safari 및 Firefox에서 초기 사례의'.style.visibility == '''을 확인했습니다. IE를 테스트하지 않았고 액세스 권한이 없습니다. – Anurag

6

추악한 순수 자바 스크립트 코드 세계에서 해결책은 좋습니다. 하지만 당신이 "우아함"이라고 말했기 때문에, 제 대답은 jQuery를 사용하는 것입니다.

나는 이벤트 기반이 아닌 행동 기반 코드를 사용하므로 코드에 정확히 일치하지는 않을 것이다. 그러나 다음과 같이 보일 것이다.

$('#Quote_app ol').click(function() { 
    if ($(this).is(':visible')) { 
    $(this).fadeOut(); 
    } else { 
    $(this).fadeIn(); 
    $('ol', $(this).parent()).not(this).fadeOut(); 
    } 
}); 

ID 이벤트는 ID가 Quote_app 인 항목 아래의 모든 ol 요소에 연결되며 현재 표시되어 있으면 숨기고 그렇지 않으면 다른 모든 ol 요소를 숨 깁니다.

+1

일부 경우 라이브러리의 장점을 이해할 수 있지만 라이브러리는 과장 될 것입니다. –

+0

또는 좋은 프레임 워크가 많기 때문에 마음에 드는 다른 프레임 워크. –

+2

jQuery는 사용할 적절한 함수를 찾으면 완벽합니다. 혼란을 없애고 (거의) 코드를 쉽게 읽을 수 있으므로 논리/아이디어가 더 잘 전달됩니다. – Mike

1

코드가 무엇을 의미하는지에 대해 확실하지 않습니다. Stratagy는 먼저 모든 항목에 대해 기본 작업을 수행 한 다음 선택한 항목에 대해 특정 작업을 수행합니다. 이런 식으로 뭔가 :

for(var i=0;i<Controls.length;i++){ 
    if(Controls[i].style.visibility=="visible"){ 

     Reveal("hide",20,0.3,Controls[i]); 

    }; 
} 
Reveal("show",20,0.3,Control); 
+0

저는 이것이 단지 개인적인 스타일이라고 생각합니다. 그리고 더 중요한 것은 여러분이 디폴트라고 생각하는 것입니다. 더 많은 요소가 표시 될 단일 요소보다 숨겨져 있으므로 요소를 숨기려면 (내 의견으로는) 기본값이되어야합니다. –

0
if(Controls[i] != Control) { 
    if(Controls[i].style.visibility == "visible"){ 
    Reveal("hide", 20, 0.3, Controls[i]); 
    }; 
} else { 
    Reveal("show", 20, 0.3, Control); 
}; 

는 다음과 같이 다시 작성할 수 있습니다 :

if (Controls[i] == Control) { 
    Reveal("show", 20, 0.3, Control); 
} else if (Controls[i].style.visibility == "visible") { 
    Reveal("hide", 20, 0.3, Controls[i]); 
} 
0

가 jQuery를 제안에서에 따르 -

jQuery를 종종에서 더욱 매력적인 beomes 토글 기능이 있습니다 이 상황은 코드를 두 줄로 줄여줍니다.

당신은이 같은 사용자 지정 애니메이션을 작성할 수 있습니다 :이 칼 Swedberg을 인용, 현재 toggleFade 기능 밤은하지만 쉽게 추가 할 수 있습니다 그리고

jQuery.fn.fadeToggle = function(speed, easing, callback) { 
    return this.animate({opacity: 'toggle'}, speed, easing, callback); 
    }; 

을, 당신은이 작업을 수행 할 수 있습니다

$(".bio-toggler").click(function() { 
    $("#bio-form").fadeToggle(); 
    }) 

;

0

Reveal("hide", ...) 기능이 표시 여부를 숨김으로 설정했다고 가정하면 getComputedStyle을 사용하지 않아도 작동합니다.

if(Controls [i] !== Control && Controls[i].style.visibility !== "hidden") { 
    Reveal("hide", 20, 0.3, Controls[i]); 
} 
+0

어떤 일을하지만 Toggle은 Click 이벤트에 의해 트리거되므로 Reveal은 컨트롤 [i] 만 먼저 숨길 수 있습니다. 이제 스크립트를 초기화하는 동안 컨트롤 숨기기 [i]로 설정했습니다. –

+0

IE에서 'getComputedStyle'을 지원하지 않습니다. 모든 브라우저에서 작동하는 방식으로 질문에 대답 할 때 제 대답을 받아 들일 수 있습니까? –

0

작은 원숭이 패치를 사용하면 외부 프레임 워크를 사용하지 않고도 훨씬 더 깨끗하게 만들 수 있습니다. 나는 또한 애니메이션의 순서가 중요하지 않다는 가정에 기초하여 논리를 개편 할 자유를 취했다.

if Control is hidden 
    loop through Controls as C 
     hide if C != Control 
     show if C = Control 
else 
    hide Control 

이 알고리즘을 해석하는 또 다른 방법이있다 - 한 Controls 적어도 하나 개의 요소 (상관 없습니다) 포함으로, Control의 가시성이 전환됩니다. 모든 (Controls minus Control)이 숨겨집니다. 그래서 저는 항상 컨트롤에 하나의 컨트롤이 있다고 가정하는 자유를 다시 얻었습니다. 그리고 Control은 항상 토글됩니다.

여기에 원숭이 패치 ++ 코드가 있습니다 (jsfiddle에도 있음). 이렇게하면 함수에서 모든 if와 elses가 제거됩니다. 여기

function Toggle(Control) { 
    var Controls = document.getElementsByTagName("ol" .. 
    var Control = Control.getElementsByTagName("ol")[0]; 

    Control.toggle(); 
    Controls.filter(function(c) { 
     return c != Control && c.isVisible(); 
    }).hide(); 
}; 

을 코드 숨김입니다 :

Toggle 기능은 이제 다음과 같습니다. 라인 3

Element.prototype.isVisible = function() { 
    return this.style.visibility == 'visible' || this.style.visibility == ''; 
}; 

Element.prototype.show = function() { 
    this.style.visibility = 'visible'; 
}; 

Element.prototype.hide = function() { 
    this.style.visibility = 'hidden'; 
}; 

Element.prototype.toggle = function() { 
    this.isVisible() ? this.hide() : this.show(); 
};